//
//  ViewController.m
//  DualMediationDemo
//
//  主界面控制器 - 功能完整版本
//

#import <UIKit/UIKit.h>
#import "ViewController.h"
#import <DualMediationSDK/DualMediationSDKPublic.h>
#import <DualMediationSDK/DMAdDelegate.h>
#import <DualMediationSDK/IMLogUtils.h>
#import <Masonry/Masonry.h>
#import <IronSource/IronSource.h>
#import <AppLovinSDK/AppLovinSDK.h>
#import <StoreKit/StoreKit.h>

@interface ViewController ()<DMAdDelegate>

// UI组件
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *logWindowToggleButton;
@property (nonatomic, strong) UIView *buttonContainerView;
@property (nonatomic, strong) UITextView *logDisplayView;
@property (nonatomic, strong) UILabel *statusLabel;

// 功能按钮
@property (nonatomic, strong) UIButton *complianceButton;
@property (nonatomic, strong) UIButton *sdkInitButton;
@property (nonatomic, strong) UIButton *checkStatusButton;
@property (nonatomic, strong) UIButton *enableDebugButton;
@property (nonatomic, strong) UIButton *showDebugLogButton;
@property (nonatomic, strong) UIButton *networkTestButton;
@property (nonatomic, strong) UIButton *simulateLogButton;
@property (nonatomic, strong) UIButton *clearLogButton;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *adStrategyButton;
@property (nonatomic, strong) UIButton *gameStrategyButton;
@property (nonatomic, strong) UIButton *fcmUploadButton;
@property (nonatomic, strong) UIButton *deviceInfoButton;
@property (nonatomic, strong) UIButton *fcmPushTestButton;
@property (nonatomic, strong) UIButton *vibrateTestButton;
@property (nonatomic, strong) UIButton *vibrateSimpleButton;
@property (nonatomic, strong) UIButton *vibratePatternButton;
@property (nonatomic, strong) UIButton *vibrateTypeButton;
@property (nonatomic, strong) UIButton *vibrateControlButton;
@property (nonatomic, strong) UIButton *vibratePresetButton;
@property (nonatomic, strong) UIButton *vibrateStatusButton;
@property (nonatomic, strong) UIButton *ironSourceDebugButton;
@property (nonatomic, strong) UIButton *maxDebugButton;

// Ad Buttons
@property (nonatomic, strong) UIButton *loadRewardedButton;
@property (nonatomic, strong) UIButton *showRewardedButton;
@property (nonatomic, strong) UIButton *loadInterstitialButton;
@property (nonatomic, strong) UIButton *showInterstitialButton;
@property (nonatomic, strong) UIButton *splashButton;
@property (nonatomic, strong) UIButton *loadBannerButton;
@property (nonatomic, strong) UIButton *hideBannerButton;
@property (nonatomic, strong) UIButton *loadNativeButton;

// Ad Views
@property (nonatomic, strong) UIView *adContainerView;

// Interstitial Ad Properties - 已移除内部组件属性，改为通过DualMediationSDKPublic统一接口调用

// Interstitial Scene Buttons
@property (nonatomic, strong) UIButton *interLevelWinButton;
@property (nonatomic, strong) UIButton *interLevelFailButton;
@property (nonatomic, strong) UIButton *interLevelRetryButton;
@property (nonatomic, strong) UIButton *interPlayTimeButton;
@property (nonatomic, strong) UIButton *interLevelWaitButton;
@property (nonatomic, strong) UIButton *setupInterstitialButton;
@property (nonatomic, strong) UIButton *setupSceneManagerButton;
@property (nonatomic, strong) UIButton *setupSceneInterceptorButton;

// Banner Scene Buttons
@property (nonatomic, strong) UIButton *bannerInitButton;
@property (nonatomic, strong) UIButton *bannerLevelEnterButton;
@property (nonatomic, strong) UIButton *bannerLevelWinButton;
@property (nonatomic, strong) UIButton *bannerShopButton;
@property (nonatomic, strong) UIButton *bannerPauseButton;
@property (nonatomic, strong) UIButton *hideBannerSceneButton;

// 日志窗口状态
@property (nonatomic, assign) BOOL isLogWindowVisible;

// 状态管理
@property (nonatomic, strong) NSMutableArray<NSString *> *logMessages;
@property (nonatomic, assign) NSInteger testStepIndex;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化数据
    [self initializeData];
    
    // 设置界面
    [self setupUserInterface];
    
    // 设置约束
    [self setupConstraints];

    // SDK初始化将在用户点击相应按钮时进行
    // 注册SDK监听器和Firebase消息推送功能已集成到DualMediationSDKPublic中
    
    // 设置统一广告代理
    [[DualMediationSDKPublic sharedInstance] setAdDelegate:self];
    
    // 启动欢迎日志
    [self addLogMessage:@"🎉 DualMediationDemo 启动完成"];
    [self addLogMessage:@"📱 准备进行SDK功能测试..."];
    
    // 启动后检查未核销订单
//    [self checkUnacknowledgedOrdersOnStartup];

    // 显示实时日志悬浮按钮，并隐藏顶部按钮
    [[DualMediationSDKPublic sharedInstance] showFloatingLogButton];
    self.logWindowToggleButton.hidden = YES;
    [self.logWindowToggleButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0);
    }];
}

#pragma mark - 初始化

- (void)initializeData {
    self.logMessages = [[NSMutableArray alloc] init];
    self.testStepIndex = 0;
    self.isLogWindowVisible = NO;
}

- (void)setupUserInterface {
    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.97 alpha:1.0];
    
    // 创建滚动视图
    [self createScrollView];
    
    // 创建顶部日志窗口切换按钮
    [self createLogWindowToggleButton];
    
    // 创建功能按钮容器
    [self createButtonContainer];
    
    // 创建功能按钮
    [self createFunctionButtons];
    
    // 创建广告按钮
    [self createAdButtons];
    
    // 创建日志显示区域
    [self createLogDisplayArea];
    
    // 创建状态标签
    [self createStatusLabel];
}

- (void)createScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView.showsVerticalScrollIndicator = YES;
    [self.view addSubview:self.scrollView];
    
    self.contentView = [[UIView alloc] init];
    self.contentView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:self.contentView];
}

- (void)createLogWindowToggleButton {
    self.logWindowToggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.logWindowToggleButton setTitle:@"📊 实时日志" forState:UIControlStateNormal];
    [self.logWindowToggleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.logWindowToggleButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.logWindowToggleButton.backgroundColor = [UIColor colorWithRed:0.6 green:0.4 blue:0.9 alpha:1.0];
    self.logWindowToggleButton.layer.cornerRadius = 12;
    self.logWindowToggleButton.layer.shadowColor = [UIColor colorWithRed:0.6 green:0.4 blue:0.9 alpha:0.5].CGColor;
    self.logWindowToggleButton.layer.shadowOffset = CGSizeMake(0, 2);
    self.logWindowToggleButton.layer.shadowOpacity = 0.3;
    self.logWindowToggleButton.layer.shadowRadius = 4;
    [self.logWindowToggleButton addTarget:self action:@selector(toggleLogWindow) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.logWindowToggleButton];
}

- (void)createButtonContainer {
    self.buttonContainerView = [[UIView alloc] init];
    self.buttonContainerView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.buttonContainerView];
}

- (void)createFunctionButtons {
    // SDK合规初始化按钮
    self.complianceButton = [self createButtonWithTitle:@"🚀 合规初始化"
                                                   color:[UIColor systemBlueColor]
                                                  action:@selector(initializeCompliance)];
    
    // SDK快速初始化按钮
    self.sdkInitButton = [self createButtonWithTitle:@"⚡ 快速初始化"
                                                color:[UIColor systemGreenColor]
                                               action:@selector(initializeSDK)];
    
    // 查看状态按钮
    self.checkStatusButton = [self createButtonWithTitle:@"📊 查看状态"
                                                    color:[UIColor systemOrangeColor]
                                                   action:@selector(checkSDKStatus)];
    
    // 启用调试模式按钮
    self.enableDebugButton = [self createButtonWithTitle:@"🔧 调试模式"
                                                    color:[UIColor systemPurpleColor]
                                                   action:@selector(enableDebugMode)];
    
    // 显示调试日志按钮
    self.showDebugLogButton = [self createButtonWithTitle:@"📋 调试日志"
                                                     color:[UIColor systemTealColor]
                                                    action:@selector(showDebugLog)];
    
    // 网络测试按钮
    self.networkTestButton = [self createButtonWithTitle:@"🌐 网络测试"
                                                    color:[UIColor systemIndigoColor]
                                                   action:@selector(runNetworkTest)];
    
    // 模拟日志按钮
    self.simulateLogButton = [self createButtonWithTitle:@"📝 模拟日志"
                                                    color:[UIColor systemBrownColor]
                                                   action:@selector(simulateLogOutput)];
    
    // 清空日志按钮
    self.clearLogButton = [self createButtonWithTitle:@"🗑️ 清空日志"
                                                 color:[UIColor systemRedColor]
                                                action:@selector(clearLogDisplay)];
    
    // 登录按钮
    self.loginButton = [self createButtonWithTitle:@"🔐 用户登录"
                                              color:[UIColor systemRedColor]
                                             action:@selector(userLogin)];
    
    // 广告策略按钮
    self.adStrategyButton = [self createButtonWithTitle:@"📊 广告策略"
                                                   color:[UIColor systemPinkColor]
                                                  action:@selector(getAdStrategy)];
    
    // 产品策略按钮
    self.gameStrategyButton = [self createButtonWithTitle:@"🎮 产品策略"
                                                     color:[UIColor colorWithRed:0.9 green:0.5 blue:0.2 alpha:1.0]
                                                    action:@selector(getGameStrategy)];
    
    // FCM令牌上传按钮
    self.fcmUploadButton = [self createButtonWithTitle:@"🔔 FCM上传"
                                                  color:[UIColor colorWithRed:0.9 green:0.5 blue:0.2 alpha:1.0]
                                                 action:@selector(uploadFCMToken)];
    
    // 设备信息按钮
    self.deviceInfoButton = [self createButtonWithTitle:@"📱 设备信息"
                                                   color:[UIColor colorWithRed:0.3 green:0.7 blue:0.9 alpha:1.0]
                                                  action:@selector(getDeviceInfo)];
    
    // FCM推送测试按钮
    self.fcmPushTestButton = [self createButtonWithTitle:@"🔔 推送测试"
                                                    color:[UIColor colorWithRed:0.8 green:0.3 blue:0.6 alpha:1.0]
                                                   action:@selector(testFCMPush)];
    
    // 震动测试按钮
    self.vibrateTestButton = [self createButtonWithTitle:@"📳 震动测试"
                                                    color:[UIColor colorWithRed:0.6 green:0.8 blue:0.3 alpha:1.0]
                                                   action:@selector(testVibrate)];
    
    // 简单震动按钮
    self.vibrateSimpleButton = [self createButtonWithTitle:@"📳 简单震动"
                                                      color:[UIColor colorWithRed:0.5 green:0.7 blue:0.9 alpha:1.0]
                                                     action:@selector(testSimpleVibrate)];
    
    // 模式震动按钮
    self.vibratePatternButton = [self createButtonWithTitle:@"🎵 模式震动"
                                                       color:[UIColor colorWithRed:0.9 green:0.5 blue:0.7 alpha:1.0]
                                                      action:@selector(testPatternVibrate)];
    
    // 类型震动按钮
    self.vibrateTypeButton = [self createButtonWithTitle:@"⚡ 类型震动"
                                                    color:[UIColor colorWithRed:0.7 green:0.9 blue:0.5 alpha:1.0]
                                                   action:@selector(testTypeVibrate)];
    
    // 震动控制按钮
    self.vibrateControlButton = [self createButtonWithTitle:@"🎛️ 震动控制"
                                                       color:[UIColor colorWithRed:0.9 green:0.7 blue:0.5 alpha:1.0]
                                                      action:@selector(testVibrateControl)];
    
    // 预设震动按钮
    self.vibratePresetButton = [self createButtonWithTitle:@"🎯 预设震动"
                                                      color:[UIColor colorWithRed:0.5 green:0.9 blue:0.7 alpha:1.0]
                                                     action:@selector(testPresetVibrate)];
    
    // 震动状态按钮
    self.vibrateStatusButton = [self createButtonWithTitle:@"📊 震动状态"
                                                      color:[UIColor colorWithRed:0.8 green:0.6 blue:0.9 alpha:1.0]
                                                     action:@selector(testVibrateStatus)];
    
    // IronSource调试按钮
    self.ironSourceDebugButton = [self createButtonWithTitle:@"🔧 IronSource调试"
                                                        color:[UIColor colorWithRed:0.2 green:0.8 blue:0.4 alpha:1.0]
                                                       action:@selector(openIronSourceDebug)];
    
    // MAX调试按钮
    self.maxDebugButton = [self createButtonWithTitle:@"🔧 MAX调试"
                                                 color:[UIColor colorWithRed:0.8 green:0.2 blue:0.4 alpha:1.0]
                                                action:@selector(openMAXDebug)];
    
    // 免广告功能按钮
    self.setRemoveAdButton = [self createButtonWithTitle:@"🚫 设置免广告"
                                                    color:[UIColor colorWithRed:0.9 green:0.3 blue:0.3 alpha:1.0]
                                                   action:@selector(setRemoveAdAction)];
    
    self.checkRemoveAdButton = [self createButtonWithTitle:@"🔍 查询免广告"
                                                      color:[UIColor colorWithRed:0.3 green:0.9 blue:0.3 alpha:1.0]
                                                     action:@selector(checkRemoveAdAction)];
    
    self.removeRewardAdButton = [self createButtonWithTitle:@"🎁❌ 禁用激励"
                                                       color:[UIColor colorWithRed:0.8 green:0.5 blue:0.2 alpha:1.0]
                                                      action:@selector(removeRewardAdAction)];
    
    self.removeInterstitialAdButton = [self createButtonWithTitle:@"📱❌ 禁用插屏"
                                                             color:[UIColor colorWithRed:0.8 green:0.2 blue:0.5 alpha:1.0]
                                                            action:@selector(removeInterstitialAdAction)];
    
    self.removeBannerAdButton = [self createButtonWithTitle:@"📰❌ 禁用横幅"
                                                       color:[UIColor colorWithRed:0.5 green:0.2 blue:0.8 alpha:1.0]
                                                      action:@selector(removeBannerAdAction)];
    
    self.removeSplashAdButton = [self createButtonWithTitle:@"🚀❌ 禁用开屏"
                                                       color:[UIColor colorWithRed:0.2 green:0.5 blue:0.8 alpha:1.0]
                                                      action:@selector(removeSplashAdAction)];
    
    self.removeNativeAdButton = [self createButtonWithTitle:@"🖼️❌ 禁用原生"
                                                       color:[UIColor colorWithRed:0.2 green:0.8 blue:0.5 alpha:1.0]
                                                      action:@selector(removeNativeAdAction)];
    
    self.removeAllAdsButton = [self createButtonWithTitle:@"🚫 禁用所有广告"
                                                     color:[UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:1.0]
                                                    action:@selector(removeAllAdsAction)];
    
    self.restoreAllAdsButton = [self createButtonWithTitle:@"✅ 恢复所有广告"
                                                      color:[UIColor colorWithRed:0.1 green:0.9 blue:0.1 alpha:1.0]
                                                     action:@selector(restoreAllAdsAction)];
    
    // Facebook功能按钮
    self.facebookLoginButton = [self createButtonWithTitle:@"📘 Facebook登录"
                                                      color:[UIColor colorWithRed:0.24 green:0.35 blue:0.60 alpha:1.0]
                                                     action:@selector(facebookLoginAction)];
    
    self.facebookLogoutButton = [self createButtonWithTitle:@"📘 Facebook登出"
                                                       color:[UIColor colorWithRed:0.20 green:0.30 blue:0.55 alpha:1.0]
                                                      action:@selector(facebookLogoutAction)];
    
    self.facebookUserInfoButton = [self createButtonWithTitle:@"👤 获取用户信息"
                                                         color:[UIColor colorWithRed:0.28 green:0.40 blue:0.65 alpha:1.0]
                                                        action:@selector(facebookGetUserInfoAction)];
    
    self.facebookShareButton = [self createButtonWithTitle:@"📤 Facebook分享"
                                                      color:[UIColor colorWithRed:0.32 green:0.45 blue:0.70 alpha:1.0]
                                                     action:@selector(facebookShareAction)];
    
    self.facebookShareImageButton = [self createButtonWithTitle:@"🖼️ 分享图片"
                                                           color:[UIColor colorWithRed:0.36 green:0.50 blue:0.75 alpha:1.0]
                                                          action:@selector(facebookShareImageAction)];
    
    self.facebookStatusButton = [self createButtonWithTitle:@"📊 Facebook状态"
                                                       color:[UIColor colorWithRed:0.40 green:0.55 blue:0.80 alpha:1.0]
                                                      action:@selector(facebookCheckStatusAction)];
    
    // 内购功能按钮
    self.launchInAppPurchaseButton = [self createButtonWithTitle:@"💰 启动内购"
                                                            color:[UIColor colorWithRed:0.85 green:0.65 blue:0.13 alpha:1.0]
                                                           action:@selector(launchInAppPurchaseAction)];
    
    self.restoreInAppPurchaseButton = [self createButtonWithTitle:@"🔄 恢复购买"
                                                             color:[UIColor colorWithRed:0.20 green:0.80 blue:0.20 alpha:1.0]
                                                            action:@selector(restoreInAppPurchaseAction)];
    
    self.requestProductListButton = [self createButtonWithTitle:@"📋 获取商品列表"
                                                           color:[UIColor colorWithRed:0.13 green:0.65 blue:0.85 alpha:1.0]
                                                          action:@selector(requestProductListAction)];
    
    self.consumableInAppPurchaseButton = [self createButtonWithTitle:@"🛒 消耗性内购"
                                                                color:[UIColor colorWithRed:0.75 green:0.45 blue:0.85 alpha:1.0]
                                                               action:@selector(consumableInAppPurchaseAction)];
    
    self.nonConsumableInAppPurchaseButton = [self createButtonWithTitle:@"💎 非消耗型内购"
                                                                   color:[UIColor colorWithRed:0.85 green:0.25 blue:0.65 alpha:1.0]
                                                                  action:@selector(nonConsumableInAppPurchaseAction)];
    
    // 核销和未核销按钮
    self.acknowledgeOrderButton = [self createButtonWithTitle:@"✅ 核销订单"
                                                         color:[UIColor colorWithRed:0.20 green:0.70 blue:0.30 alpha:1.0]
                                                        action:@selector(acknowledgeOrderAction)];
    
    self.fetchUnacknowledgedOrdersButton = [self createButtonWithTitle:@"📋 查询未核销"
                                                                  color:[UIColor colorWithRed:0.70 green:0.30 blue:0.20 alpha:1.0]
                                                                 action:@selector(fetchUnacknowledgedOrdersAction)];
    
    // 实时日志功能按钮
    self.enableLogMonitoringButton = [self createButtonWithTitle:@"📡 启用日志监听"
                                                            color:[UIColor colorWithRed:0.2 green:0.7 blue:0.9 alpha:1.0]
                                                           action:@selector(enableLogMonitoring)];
    
    self.disableLogMonitoringButton = [self createButtonWithTitle:@"📡❌ 禁用日志监听"
                                                             color:[UIColor colorWithRed:0.9 green:0.7 blue:0.2 alpha:1.0]
                                                            action:@selector(disableLogMonitoring)];
    
    self.setLogLevelInfoButton = [self createButtonWithTitle:@"📊 设置Info级别"
                                                        color:[UIColor colorWithRed:0.3 green:0.8 blue:0.5 alpha:1.0]
                                                       action:@selector(setLogLevelToInfo)];
    
    self.setLogLevelVerboseButton = [self createButtonWithTitle:@"📊 设置Verbose级别"
                                                           color:[UIColor colorWithRed:0.5 green:0.8 blue:0.3 alpha:1.0]
                                                          action:@selector(setLogLevelToVerbose)];
    
    self.clearRealTimeLogButton = [self createButtonWithTitle:@"🗑️ 清除实时日志"
                                                         color:[UIColor colorWithRed:0.9 green:0.3 blue:0.3 alpha:1.0]
                                                        action:@selector(clearRealTimeLog)];
    
    self.exportRealTimeLogButton = [self createButtonWithTitle:@"📤 导出实时日志"
                                                          color:[UIColor colorWithRed:0.7 green:0.5 blue:0.9 alpha:1.0]
                                                         action:@selector(exportRealTimeLog)];
    
    self.getLogStatisticsButton = [self createButtonWithTitle:@"📈 日志统计"
                                                         color:[UIColor colorWithRed:0.9 green:0.5 blue:0.7 alpha:1.0]
                                                        action:@selector(getLogStatistics)];
    
    self.searchLogContentButton = [self createButtonWithTitle:@"🔍 搜索日志"
                                                         color:[UIColor colorWithRed:0.5 green:0.9 blue:0.7 alpha:1.0]
                                                        action:@selector(searchLogContent)];
    
    // 应用信息按钮
    self.appInfoButton = [self createButtonWithTitle:@"📱 应用信息"
                                                color:[UIColor colorWithRed:0.2 green:0.5 blue:0.8 alpha:1.0]
                                               action:@selector(showAppInfoAction)];
    
    // 评分引导按钮
    self.reviewGuideButton = [self createButtonWithTitle:@"⭐️ 评分引导"
                                                   color:[UIColor systemYellowColor]
                                                  action:@selector(showReviewGuideAction)];
    
    // 将按钮添加到容器
    NSArray *buttons = @[self.complianceButton, self.sdkInitButton, self.checkStatusButton,
                        self.enableDebugButton, self.showDebugLogButton, self.networkTestButton,
                        self.simulateLogButton, self.clearLogButton, self.loginButton, self.adStrategyButton,
                        self.gameStrategyButton, self.fcmUploadButton, self.deviceInfoButton,
                        self.fcmPushTestButton, self.vibrateTestButton, self.vibrateSimpleButton,
                        self.vibratePatternButton, self.vibrateTypeButton, self.vibrateControlButton,
                        self.vibratePresetButton, self.vibrateStatusButton, self.ironSourceDebugButton, self.maxDebugButton,
                        self.setRemoveAdButton, self.checkRemoveAdButton, self.removeRewardAdButton,
                        self.removeInterstitialAdButton, self.removeBannerAdButton, self.removeSplashAdButton,
                        self.removeNativeAdButton, self.removeAllAdsButton, self.restoreAllAdsButton,
                        self.facebookLoginButton, self.facebookLogoutButton, self.facebookUserInfoButton,
                        self.facebookShareButton, self.facebookShareImageButton, self.facebookStatusButton,
                        self.launchInAppPurchaseButton, self.restoreInAppPurchaseButton, self.requestProductListButton,
                        self.consumableInAppPurchaseButton, self.nonConsumableInAppPurchaseButton,
                        self.acknowledgeOrderButton, self.fetchUnacknowledgedOrdersButton,
                        self.enableLogMonitoringButton, self.disableLogMonitoringButton, self.setLogLevelInfoButton,
                        self.setLogLevelVerboseButton, self.clearRealTimeLogButton, self.exportRealTimeLogButton,
                        self.getLogStatisticsButton, self.searchLogContentButton, self.appInfoButton,
                        self.reviewGuideButton];
    
    for (UIButton *button in buttons) {
        [self.buttonContainerView addSubview:button];
    }
}

- (void)createAdButtons {
    self.loadRewardedButton = [self createButtonWithTitle:@"🎁 加载激励" color:[UIColor colorWithRed:0.2 green:0.6 blue:0.8 alpha:1.0] action:@selector(loadRewarded)];
    self.showRewardedButton = [self createButtonWithTitle:@"🎁 显示激励" color:[UIColor colorWithRed:0.1 green:0.5 blue:0.7 alpha:1.0] action:@selector(showRewarded)];
    self.loadInterstitialButton = [self createButtonWithTitle:@"📱 加载插屏" color:[UIColor colorWithRed:0.8 green:0.4 blue:0.2 alpha:1.0] action:@selector(loadInterstitial)];
    self.showInterstitialButton = [self createButtonWithTitle:@"📱 显示插屏" color:[UIColor colorWithRed:0.7 green:0.3 blue:0.1 alpha:1.0] action:@selector(showInterstitial)];
    self.splashButton = [self createButtonWithTitle:@"🚀 开屏广告" color:[UIColor colorWithRed:0.9 green:0.2 blue:0.5 alpha:1.0] action:@selector(showSplash)];
    self.loadBannerButton = [self createButtonWithTitle:@"📰 加载横幅" color:[UIColor colorWithRed:0.6 green:0.2 blue:0.8 alpha:1.0] action:@selector(loadBanner)];
    self.hideBannerButton = [self createButtonWithTitle:@"📰 隐藏横幅" color:[UIColor colorWithRed:0.6 green:0.2 blue:0.8 alpha:1.0] action:@selector(hideBanner)];
    self.loadNativeButton = [self createButtonWithTitle:@"🖼️ 加载原生" color:[UIColor colorWithRed:0.4 green:0.7 blue:0.3 alpha:1.0] action:@selector(loadNative)];
    
    // 插屏广告场景按钮
    self.setupInterstitialButton = [self createButtonWithTitle:@"⚙️ 初始化插屏" color:[UIColor colorWithRed:0.3 green:0.5 blue:0.9 alpha:1.0] action:@selector(setupInterstitialManager)];
    self.setupSceneManagerButton = [self createButtonWithTitle:@"🎯 场景管理器" color:[UIColor colorWithRed:0.5 green:0.3 blue:0.9 alpha:1.0] action:@selector(setupSceneManagerExample)];
    self.setupSceneInterceptorButton = [self createButtonWithTitle:@"🛡️ 场景拦截器" color:[UIColor colorWithRed:0.9 green:0.3 blue:0.5 alpha:1.0] action:@selector(setupSceneInterceptorExample)];
    self.interLevelWinButton = [self createButtonWithTitle:@"🏆 关卡胜利" color:[UIColor colorWithRed:0.2 green:0.8 blue:0.3 alpha:1.0] action:@selector(showInterLevelWin)];
    self.interLevelFailButton = [self createButtonWithTitle:@"💀 关卡失败" color:[UIColor colorWithRed:0.8 green:0.2 blue:0.3 alpha:1.0] action:@selector(showInterLevelFail)];
    self.interLevelRetryButton = [self createButtonWithTitle:@"🔄 关卡重玩" color:[UIColor colorWithRed:0.8 green:0.6 blue:0.2 alpha:1.0] action:@selector(showInterLevelRetry)];
    self.interPlayTimeButton = [self createButtonWithTitle:@"⏰ 游戏时长" color:[UIColor colorWithRed:0.6 green:0.8 blue:0.2 alpha:1.0] action:@selector(showInterPlayTime)];
    self.interLevelWaitButton = [self createButtonWithTitle:@"⏳ 关卡等待" color:[UIColor colorWithRed:0.2 green:0.6 blue:0.8 alpha:1.0] action:@selector(showInterLevelWait)];
    
    // Banner场景按钮
    self.bannerInitButton = [self createButtonWithTitle:@"🏠 游戏主页Banner" color:[UIColor colorWithRed:0.3 green:0.7 blue:0.9 alpha:1.0] action:@selector(showBannerInit)];
    self.bannerLevelEnterButton = [self createButtonWithTitle:@"🚪 关卡进入Banner" color:[UIColor colorWithRed:0.4 green:0.8 blue:0.6 alpha:1.0] action:@selector(showBannerLevelEnter)];
    self.bannerLevelWinButton = [self createButtonWithTitle:@"🏆 关卡胜利Banner" color:[UIColor colorWithRed:0.9 green:0.7 blue:0.3 alpha:1.0] action:@selector(showBannerLevelWin)];
    self.bannerShopButton = [self createButtonWithTitle:@"🛒 商店页面Banner" color:[UIColor colorWithRed:0.8 green:0.5 blue:0.9 alpha:1.0] action:@selector(showBannerShop)];
    self.bannerPauseButton = [self createButtonWithTitle:@"⏸️ 游戏暂停Banner" color:[UIColor colorWithRed:0.6 green:0.9 blue:0.4 alpha:1.0] action:@selector(showBannerPause)];
    self.hideBannerSceneButton = [self createButtonWithTitle:@"❌ 隐藏场景Banner" color:[UIColor colorWithRed:0.9 green:0.4 blue:0.4 alpha:1.0] action:@selector(hideBannerScene)];
    
    // 原生广告场景化按钮
    self.showNativeTopButton = [self createButtonWithTitle:@"🖼️⬆️ 原生顶部" color:[UIColor colorWithRed:0.3 green:0.8 blue:0.5 alpha:1.0] action:@selector(showNativeTopAction:)];
    self.showNativeBottomButton = [self createButtonWithTitle:@"🖼️⬇️ 原生底部" color:[UIColor colorWithRed:0.5 green:0.8 blue:0.3 alpha:1.0] action:@selector(showNativeBottomAction:)];
    self.hideNativeButton = [self createButtonWithTitle:@"🖼️❌ 隐藏原生" color:[UIColor colorWithRed:0.8 green:0.3 blue:0.5 alpha:1.0] action:@selector(hideNativeAction:)];
    self.checkNativeReadyButton = [self createButtonWithTitle:@"🖼️✅ 原生就绪" color:[UIColor colorWithRed:0.6 green:0.5 blue:0.8 alpha:1.0] action:@selector(checkNativeReadyAction:)];

    NSArray *adButtons = @[self.loadRewardedButton, self.showRewardedButton, self.loadInterstitialButton, self.showInterstitialButton, self.splashButton, self.loadBannerButton, self.hideBannerButton, self.loadNativeButton, self.setupInterstitialButton, self.setupSceneManagerButton, self.setupSceneInterceptorButton, self.interLevelWinButton, self.interLevelFailButton, self.interLevelRetryButton, self.interPlayTimeButton, self.interLevelWaitButton, self.bannerInitButton, self.bannerLevelEnterButton, self.bannerLevelWinButton, self.bannerShopButton, self.bannerPauseButton, self.hideBannerSceneButton, self.showNativeTopButton, self.showNativeBottomButton, self.hideNativeButton, self.checkNativeReadyButton];
    for (UIButton *button in adButtons) {
        [self.buttonContainerView addSubview:button];
    }
}

- (UIButton *)createButtonWithTitle:(NSString *)title color:(UIColor *)color action:(SEL)action {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    button.titleLabel.adjustsFontSizeToFitWidth = YES;
    button.titleLabel.minimumScaleFactor = 0.8;
    button.backgroundColor = color;
    button.layer.cornerRadius = 10;
    button.layer.shadowColor = color.CGColor;
    button.layer.shadowOffset = CGSizeMake(0, 2);
    button.layer.shadowOpacity = 0.4;
    button.layer.shadowRadius = 3;
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    
    // 添加点击动画效果
    [button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
    [button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
    
    return button;
}

- (void)createLogDisplayArea {
    self.logDisplayView = [[UITextView alloc] init];
    self.logDisplayView.backgroundColor = [UIColor colorWithRed:0.05 green:0.05 blue:0.05 alpha:1.0];
    self.logDisplayView.textColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:1.0];
    self.logDisplayView.font = [UIFont fontWithName:@"Menlo" size:12];
    self.logDisplayView.editable = NO;
    self.logDisplayView.layer.cornerRadius = 8;
    self.logDisplayView.layer.borderWidth = 1;
    self.logDisplayView.layer.borderColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1.0].CGColor;
    self.logDisplayView.text = @"📋 日志显示区域已就绪，等待操作...\n";
    [self.contentView addSubview:self.logDisplayView];
    
    self.adContainerView = [[UIView alloc] init];
    self.adContainerView.backgroundColor = [UIColor clearColor];
    self.adContainerView.hidden = YES;
    [self.contentView addSubview:self.adContainerView];
}

- (void)createStatusLabel {
    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.text = @"📱 状态: 就绪 | 📊 日志行数: 0 | 🔧 调试: 关闭";
    self.statusLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
    self.statusLabel.font = [UIFont systemFontOfSize:12];
    self.statusLabel.textAlignment = NSTextAlignmentCenter;
    self.statusLabel.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    self.statusLabel.layer.cornerRadius = 4;
    self.statusLabel.layer.masksToBounds = YES;
    [self.view addSubview:self.statusLabel];
}

#pragma mark - 约束设置

- (void)setupConstraints {
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.statusLabel.mas_top).offset(-8);
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [self.logWindowToggleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(20);
        make.left.equalTo(self.contentView).offset(20);
        make.right.equalTo(self.contentView).offset(-20);
        make.height.mas_equalTo(50);
    }];
    
    [self.buttonContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logWindowToggleButton.mas_bottom).offset(20);
        make.left.equalTo(self.contentView).offset(20);
        make.right.equalTo(self.contentView).offset(-20);
        // 移除固定高度，改为动态高度，底部约束将在setupButtonConstraints中设置
    }];
    
    [self setupButtonConstraints];
    
    [self.adContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonContainerView.mas_bottom).offset(20);
        make.left.equalTo(self.contentView).offset(20);
        make.right.equalTo(self.contentView).offset(-20);
        make.height.mas_equalTo(0); // Hidden by default
    }];

    [self.logDisplayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonContainerView.mas_bottom).offset(20);
        make.left.equalTo(self.contentView).offset(20);
        make.right.equalTo(self.contentView).offset(-20);
        make.height.mas_greaterThanOrEqualTo(300);
        make.bottom.equalTo(self.contentView).offset(-20);
    }];
    
    [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        make.height.mas_equalTo(30);
    }];
}

- (void)setupButtonConstraints {
    NSArray *functionalButtons = @[self.complianceButton, self.sdkInitButton, self.checkStatusButton,
                                   self.enableDebugButton, self.showDebugLogButton, self.networkTestButton,
                                   self.simulateLogButton, self.clearLogButton, self.loginButton, self.adStrategyButton, self.gameStrategyButton, self.fcmUploadButton, self.deviceInfoButton,
                                   self.fcmPushTestButton, self.vibrateTestButton, self.vibrateSimpleButton,
                                   self.vibratePatternButton, self.vibrateTypeButton, self.vibrateControlButton,
                                   self.vibratePresetButton, self.vibrateStatusButton, self.ironSourceDebugButton, self.maxDebugButton,
                                   self.setRemoveAdButton, self.checkRemoveAdButton, self.removeRewardAdButton,
                                   self.removeInterstitialAdButton, self.removeBannerAdButton, self.removeSplashAdButton,
                                   self.removeNativeAdButton, self.removeAllAdsButton, self.restoreAllAdsButton,
                                   self.facebookLoginButton, self.facebookLogoutButton, self.facebookUserInfoButton,
                                   self.facebookShareButton, self.facebookShareImageButton, self.facebookStatusButton,
                                   self.launchInAppPurchaseButton, self.restoreInAppPurchaseButton, self.requestProductListButton,
                                   self.consumableInAppPurchaseButton, self.nonConsumableInAppPurchaseButton,
                                   self.acknowledgeOrderButton, self.fetchUnacknowledgedOrdersButton,
                                   self.enableLogMonitoringButton, self.disableLogMonitoringButton, self.setLogLevelInfoButton,
                                   self.setLogLevelVerboseButton, self.clearRealTimeLogButton, self.exportRealTimeLogButton,
                                   self.getLogStatisticsButton, self.searchLogContentButton, self.appInfoButton,
                                   self.reviewGuideButton];
    
    NSArray *adButtons = @[self.loadRewardedButton, self.showRewardedButton, self.loadInterstitialButton,
                           self.showInterstitialButton, self.loadBannerButton,self.hideBannerButton, self.loadNativeButton,self.splashButton,
                           self.setupInterstitialButton, self.setupSceneManagerButton, self.setupSceneInterceptorButton,
                           self.interLevelWinButton, self.interLevelFailButton, self.interLevelRetryButton,
                           self.interPlayTimeButton, self.interLevelWaitButton, self.bannerInitButton,
                           self.bannerLevelEnterButton, self.bannerLevelWinButton, self.bannerShopButton,
                           self.bannerPauseButton, self.hideBannerSceneButton];
    
    CGFloat buttonHeight = 45;
    CGFloat verticalSpacing = 12;
    CGFloat horizontalSpacing = 12;
    
    // 设置功能按钮约束 - 2列布局
    for (int i = 0; i < functionalButtons.count; i++) {
        UIButton *button = functionalButtons[i];
        int row = i / 2;
        int col = i % 2;
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(buttonHeight);
            
            // 设置垂直位置
            if (row == 0) {
                make.top.equalTo(self.buttonContainerView).offset(0);
            } else {
                UIButton *prevRowButton = functionalButtons[i - 2];
                make.top.equalTo(prevRowButton.mas_bottom).offset(verticalSpacing);
            }
            
            // 设置水平位置
            if (col == 0) {
                // 左列
                make.left.equalTo(self.buttonContainerView);
                make.right.equalTo(self.buttonContainerView.mas_centerX).offset(-horizontalSpacing/2);
            } else {
                // 右列
                make.left.equalTo(self.buttonContainerView.mas_centerX).offset(horizontalSpacing/2);
                make.right.equalTo(self.buttonContainerView);
            }
        }];
    }
    
    // 设置广告按钮约束 - 2列布局
    UIButton *lastFunctionalButton = functionalButtons.lastObject;
    CGFloat adButtonsTopOffset = verticalSpacing * 2;
    
    for (int i = 0; i < adButtons.count; i++) {
        UIButton *button = adButtons[i];
        int row = i / 2;
        int col = i % 2;
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(buttonHeight);
            
            // 设置垂直位置
            if (row == 0) {
                make.top.equalTo(lastFunctionalButton.mas_bottom).offset(adButtonsTopOffset);
            } else {
                UIButton *prevRowButton = adButtons[i - 2];
                make.top.equalTo(prevRowButton.mas_bottom).offset(verticalSpacing);
            }
            
            // 设置水平位置
            if (col == 0) {
                // 左列
                make.left.equalTo(self.buttonContainerView);
                make.right.equalTo(self.buttonContainerView.mas_centerX).offset(-horizontalSpacing/2);
            } else {
                // 右列
                make.left.equalTo(self.buttonContainerView.mas_centerX).offset(horizontalSpacing/2);
                make.right.equalTo(self.buttonContainerView);
            }
        }];
    }
    
    // 设置buttonContainerView的底部约束，让它的高度根据最后一排按钮自动调整
    UIButton *lastAdButton = adButtons.lastObject;
    [self.buttonContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastAdButton.mas_bottom);
    }];
}

#pragma mark - 日志窗口管理

- (void)toggleLogWindow {
    // 通过DualMediationSDKPublic接口控制实时日志窗口
    if ([[DualMediationSDKPublic sharedInstance] isRealTimeLogWindowVisible]) {
        [self hideLogWindow];
    } else {
        [self showLogWindow];
    }
}

#pragma mark - 评分引导

- (void)showReviewGuideAction {
    [self addLogMessage:@"⭐️ 尝试触发系统评分引导..."];
    
    BOOL didRequest = NO;
    
#if defined(__IPHONE_14_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0)
    if (@available(iOS 14.0, *)) {
        UIWindowScene *scene = self.view.window.windowScene;
        if (scene) {
            [SKStoreReviewController requestReviewInScene:scene];
            didRequest = YES;
        }
    }
#endif
    
    if (!didRequest) {
        if (@available(iOS 10.3, *)) {
            [SKStoreReviewController requestReview];
            didRequest = YES;
        }
    }
    
    if (didRequest) {
        [self addLogMessage:@"✅ 已请求系统评分弹窗（是否显示由系统决定）"];
    } else {
        [self addLogMessage:@"⚠️ 当前系统版本不支持内置评分弹窗"];
    }
}

- (void)showLogWindow {
    // 通过DualMediationSDKPublic显示实时日志窗口
    [[DualMediationSDKPublic sharedInstance] showRealTimeLogWindow];
    
    // 启用IMLogUtils监听
    [[DualMediationSDKPublic sharedInstance] enableRealTimeLogMonitoring:YES];
    
    // 设置日志级别为详细模式
    [[DualMediationSDKPublic sharedInstance] setRealTimeLogMinimumLevel:IMLogLevelVerbose];
    
    self.isLogWindowVisible = YES;
    [self.logWindowToggleButton setTitle:@"📊 隐藏日志" forState:UIControlStateNormal];
    
    [self addLogMessage:@"📊 实时日志弹窗已显示（通过DualMediationSDKPublic）"];
}

- (void)hideLogWindow {
    // 通过DualMediationSDKPublic隐藏实时日志窗口
    [[DualMediationSDKPublic sharedInstance] hideRealTimeLogWindow];
    
    self.isLogWindowVisible = NO;
    [self.logWindowToggleButton setTitle:@"📊 实时日志" forState:UIControlStateNormal];
    
    [self addLogMessage:@"📊 实时日志弹窗已隐藏（通过DualMediationSDKPublic）"];
}

#pragma mark - 实时日志功能演示

- (void)enableLogMonitoring {
    [self addLogMessage:@"🔊 启用实时日志监听..."];
    [[DualMediationSDKPublic sharedInstance] enableRealTimeLogMonitoring:YES];
    [self addLogMessage:@"✅ 实时日志监听已启用"];
}

- (void)disableLogMonitoring {
    [self addLogMessage:@"🔇 禁用实时日志监听..."];
    [[DualMediationSDKPublic sharedInstance] enableRealTimeLogMonitoring:NO];
    [self addLogMessage:@"✅ 实时日志监听已禁用"];
}

- (void)setLogLevelToInfo {
    [self addLogMessage:@"📊 设置日志级别为Info..."];
    [[DualMediationSDKPublic sharedInstance] setRealTimeLogMinimumLevel:IMLogLevelInfo];
    [self addLogMessage:@"✅ 日志级别已设置为Info"];
}

- (void)setLogLevelToVerbose {
    [self addLogMessage:@"📊 设置日志级别为Verbose..."];
    [[DualMediationSDKPublic sharedInstance] setRealTimeLogMinimumLevel:IMLogLevelVerbose];
    [self addLogMessage:@"✅ 日志级别已设置为Verbose"];
}

- (void)clearRealTimeLog {
    [self addLogMessage:@"🗑️ 清除实时日志..."];
    [[DualMediationSDKPublic sharedInstance] clearRealTimeLogWindow];
    [self addLogMessage:@"✅ 实时日志已清除"];
}

- (void)exportRealTimeLog {
    [self addLogMessage:@"📤 导出实时日志..."];
    [[DualMediationSDKPublic sharedInstance] exportRealTimeLogsWithSystemLogs:YES completion:^(NSString * _Nullable filePath, NSError * _Nullable error) {
        if (filePath) {
            [self addLogMessage:[NSString stringWithFormat:@"✅ 日志导出成功: %@", filePath]];
        } else {
            [self addLogMessage:[NSString stringWithFormat:@"❌ 日志导出失败: %@", error.localizedDescription]];
        }
    }];
}

- (void)getLogStatistics {
    [self addLogMessage:@"📊 获取日志统计信息..."];
    NSDictionary *stats = [[DualMediationSDKPublic sharedInstance] getRealTimeLogStatistics];
    [self addLogMessage:[NSString stringWithFormat:@"📈 日志统计: %@", stats]];
}

- (void)searchLogContent {
    [self addLogMessage:@"🔍 搜索日志内容..."];
    [[DualMediationSDKPublic sharedInstance] searchRealTimeLogs:@"SDK" caseSensitive:NO];
    [self addLogMessage:@"🔍 已在实时日志窗口中搜索包含'SDK'的日志"];
}

#pragma mark - 广告容器管理

- (void)showAdContainer {
    self.adContainerView.hidden = NO;
    [self.adContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(250);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)hideAdContainer {
    [self.adContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.adContainerView.hidden = YES;
    }];
}

#pragma mark - 按钮动画效果

- (void)buttonTouchDown:(UIButton *)sender {
    [UIView animateWithDuration:0.1 animations:^{
        sender.transform = CGAffineTransformMakeScale(0.95, 0.95);
        sender.alpha = 0.8;
    }];
}

- (void)buttonTouchUp:(UIButton *)sender {
    [UIView animateWithDuration:0.1 animations:^{
        sender.transform = CGAffineTransformIdentity;
        sender.alpha = 1.0;
    }];
}

#pragma mark - SDK功能调用

- (void)initializeCompliance {
    [self addLogMessage:@"🚀 开始初始化SDK合规管理..."];
    
    // 注意：DualMediationSDKPublic 不提供单独的合规初始化方法
    // 合规检查已集成在SDK初始化过程中
    [self addLogMessage:@"ℹ️ 合规检查已集成在SDK初始化过程中"];
    [self addLogMessage:@"📋 请使用快速初始化SDK按钮进行完整初始化"];
    [self updateStatusLabel];
}

- (void)initializeSDK {
    [self addLogMessage:@"⚡ 开始快速初始化SDK..."];
    // 初始化DualMediationSDK
    [DualMediationSDKPublic IninSDKWithCompletion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ SDK初始化成功"];
        } else {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ SDK初始化失败: %@", error.localizedDescription];
        }
    }];
    
    // 添加日志信息
    dispatch_async(dispatch_get_main_queue(), ^{
        [self addLogMessage:[NSString stringWithFormat:@"✅ SDK快速启动已调用"]];
        [self addLogMessage:@"📱 广告SDK快速启动中..."];
        [self updateStatusLabel];
    });
}

- (void)checkSDKStatus {
    [self addLogMessage:@"📊 检查SDK状态..."];
    
    DualMediationSDKPublic *sdk = [DualMediationSDKPublic sharedInstance];
    
    [self addLogMessage:[NSString stringWithFormat:@"📱 SDK版本: %@", sdk.sdkVersion]];
    [self addLogMessage:[NSString stringWithFormat:@"🔧 SDK已初始化: %@", sdk.isSDKInitialized ? @"是" : @"否"]];
    [self addLogMessage:[NSString stringWithFormat:@"📋 合规已完成: %@", sdk.isComplianceCompleted ? @"是" : @"否"]];
    [self addLogMessage:[NSString stringWithFormat:@"🐛 调试模式: %@", sdk.isDebugModeEnabled ? @"开启" : @"关闭"]];
    
    [self updateStatusLabel];
}

- (void)enableDebugMode {
    [self addLogMessage:@"🔧 启用调试模式..."];
    
    [[DualMediationSDKPublic sharedInstance] setDebugModeEnabled:YES];
    
    [self addLogMessage:@"✅ 调试模式已启用"];
    [self addLogMessage:@"📊 详细日志输出已开启"];
    [self updateStatusLabel];
}

- (void)showDebugLog {
    [self addLogMessage:@"📋 启用调试模式查看日志..."];
    
    // 注意：DualMediationSDKPublic 不提供 showDebugLogWindow 方法
    // 可以使用调试模式来查看日志
    [[DualMediationSDKPublic sharedInstance] setDebugModeEnabled:YES];
    [self addLogMessage:@"🐛 调试模式已启用，可在控制台查看详细日志"];
}

- (void)runNetworkTest {
    [self addLogMessage:@"🌐 开始运行网络工具测试..."];
    
    // 模拟网络测试过程
    self.testStepIndex = 0;
    [self simulateNetworkTestStep];
}

- (void)simulateNetworkTestStep {
    NSArray *testSteps = @[
        @"🌐 模拟网络配置初始化...",
        @"📡 模拟GET请求测试...",
        @"📤 模拟POST请求测试...",
        @"📁 模拟文件上传测试...",
        @"📥 模拟文件下载测试...",
        @"🔧 模拟网络状态监控...",
        @"🔍 模拟请求管理测试...",
        @"🔒 模拟SSL配置测试...",
        @"💾 模拟缓存管理测试...",
        @"📊 模拟网络统计测试..."
    ];
    
    if (self.testStepIndex < testSteps.count) {
        [self addLogMessage:testSteps[self.testStepIndex]];
        self.testStepIndex++;
        
        // 模拟测试延迟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self simulateNetworkTestStep];
        });
    } else {
        [self addLogMessage:@"✅ 所有网络测试已完成！"];
        [self addLogMessage:@"📊 网络工具功能说明..."];
        [self addLogMessage:@"ℹ️ 要使用真实的网络功能，请添加相应的工具类文件"];
        [self addLogMessage:@"ℹ️ 网络工具特性：基于AFNetworking 4.0，完整HTTP支持"];
    }
}

- (void)simulateLogOutput {
    [self addLogMessage:@"📝 模拟日志输出..."];
    
    // 模拟不同级别的日志
    [IMLogUtils verbose:IMLogTagGeneral format:@"详细日志示例"];
    [IMLogUtils debug:IMLogTagGeneral format:@"调试日志示例"];
    [IMLogUtils info:IMLogTagGeneral format:@"信息日志示例"];
    [IMLogUtils warning:IMLogTagGeneral format:@"警告日志示例"];
    [IMLogUtils error:IMLogTagGeneral format:@"错误日志示例"];
    
    [self addLogMessage:@"✅ 已输出各级别日志到IMLogUtils"];
    [self addLogMessage:@"📊 可在实时日志弹窗中查看详细输出"];
}

- (void)clearLogDisplay {
    [self addLogMessage:@"🗑️ 清空日志显示..."];
    
    // 使用主线程清理日志与更新UI，保证与 addLogMessage 的访问一致
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.logMessages removeAllObjects];
        self.logDisplayView.text = @"📋 日志已清空，等待新的操作...\n";
        
        [self updateStatusLabel];
    });
}

- (void)userLogin {
    [self addLogMessage:@"🔐 开始用户登录..."];
    
    // 检查SDK是否已初始化
    if (![[DualMediationSDKPublic sharedInstance] isSDKInitialized]) {
        [self addLogMessage:@"❌ SDK未初始化，请先点击'🚀 合规初始化'或'⚡ 快速初始化'按钮"];
        [self addLogMessage:@"💡 提示：登录功能需要在SDK初始化完成后才能使用"];
        return;
    }
    
    // 获取或生成登录用的UUID（通过DualMediationSDKPublic统一接口）
    NSString *deviceUUID = [[DualMediationSDKPublic sharedInstance] getOrCreateLoginUUID];
    NSString *appId = @"ywoeq0rgljb6ydjh"; // 示例应用ID
    NSString *countryCode = @"CN"; // 示例地区代码
    
    [self addLogMessage:[NSString stringWithFormat:@"📱 设备UUID: %@", deviceUUID]];
    [self addLogMessage:[NSString stringWithFormat:@"🆔 应用ID: %@", appId]];
    [self addLogMessage:[NSString stringWithFormat:@"🌍 地区代码: %@", countryCode]];
    
    // 调用登录接口
    [[DualMediationSDKPublic sharedInstance] loginWithAppId:appId
                                                    iosUuid:deviceUUID
                                                countryCode:countryCode
                                                 completion:^(BOOL success, NSDictionary * _Nullable userInfo, NSError * _Nullable error) {
        if (success) {
             [self addLogMessage:@"✅ 登录成功！"];
             [self addLogMessage:[NSString stringWithFormat:@"👤 用户ID: %@", userInfo[@"userId"] ?: @"未知"]];
             [self addLogMessage:[NSString stringWithFormat:@"📅 注册时间: %@", userInfo[@"regTs"] ?: @"未知"]];
             [self addLogMessage:[NSString stringWithFormat:@"💬 消息: %@", userInfo[@"message"] ?: @"无"]];
             [self addLogMessage:[NSString stringWithFormat:@"⏰ 时间戳: %.0f", [userInfo[@"timestamp"] doubleValue]]];
        } else {
            [self addLogMessage:@"❌ 登录失败！"];
            [self addLogMessage:[NSString stringWithFormat:@"🚫 错误信息: %@", error.localizedDescription ?: @"未知错误"]];
            [self addLogMessage:[NSString stringWithFormat:@"🔢 错误代码: %ld", (long)error.code]];
        }
        
        [self updateStatusLabel];
    }];
}

- (void)getAdStrategy {
    [self addLogMessage:@"📊 开始获取广告策略..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法获取广告策略"];
        [self addLogMessage:@"💡 提示：广告策略功能需要在SDK初始化完成后才能使用"];
        return;
    }
    
    // 获取登录用的UUID（通过DualMediationSDKPublic统一接口）和应用ID
    NSString *deviceUUID = [[DualMediationSDKPublic sharedInstance] getOrCreateLoginUUID];
    NSString *appId = @"ywoeq0rgljb6ydjh"; // 示例应用ID
    
    [self addLogMessage:[NSString stringWithFormat:@"📱 设备UUID: %@", deviceUUID]];
    [self addLogMessage:[NSString stringWithFormat:@"🆔 应用ID: %@", appId]];
    
    // 调用广告策略接口
    [[DualMediationSDKPublic sharedInstance] getAdStrategyWithAppId:appId
                                                               uuid:deviceUUID
                                                         completion:^(BOOL success, id _Nullable response, NSError * _Nullable error) {
        if (success && response) {
            [self addLogMessage:@"✅ 获取广告策略成功！"];
            [self addLogMessage:[NSString stringWithFormat:@"📊 响应数据: %@", response]];
            
            // 如果response是IMAdStrategyResponse对象，可以进一步解析
            if ([response respondsToSelector:@selector(message)]) {
                [self addLogMessage:[NSString stringWithFormat:@"💬 服务器消息: %@", [response valueForKey:@"message"]]];
            }
            if ([response respondsToSelector:@selector(data)]) {
                id data = [response valueForKey:@"data"];
                [self addLogMessage:[NSString stringWithFormat:@"📋 策略数据: %@", data]];
            }
        } else {
            [self addLogMessage:@"❌ 获取广告策略失败！"];
            [self addLogMessage:[NSString stringWithFormat:@"🚫 错误信息: %@", error.localizedDescription ?: @"未知错误"]];
            [self addLogMessage:[NSString stringWithFormat:@"🔢 错误代码: %ld", (long)error.code]];
        }
        
        [self updateStatusLabel];
    }];
}

- (void)getGameStrategy {
    [self addLogMessage:@"🎮 开始获取产品策略..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法获取产品策略"];
        [self addLogMessage:@"💡 提示：产品策略功能需要在SDK初始化完成后才能使用"];
        return;
    }
    
    // 获取登录用的UUID（通过DualMediationSDKPublic统一接口）和应用ID
    NSString *deviceUUID = [[DualMediationSDKPublic sharedInstance] getOrCreateLoginUUID];
    NSString *appId = @"ywoeq0rgljb6ydjh"; // 示例应用ID
    
    [self addLogMessage:[NSString stringWithFormat:@"📱 设备UUID: %@", deviceUUID]];
    [self addLogMessage:[NSString stringWithFormat:@"🆔 应用ID: %@", appId]];
    
    // 调用产品策略接口
    [[DualMediationSDKPublic sharedInstance] getGameStrategyWithAppId:appId
                                                                 uuid:deviceUUID
                                                           completion:^(BOOL success, NSArray * _Nullable strategyData, NSError * _Nullable error) {
        if (success && strategyData) {
            [self addLogMessage:@"✅ 获取产品策略成功！"];
            [self addLogMessage:[NSString stringWithFormat:@"📊 策略场景数量: %lu", (unsigned long)strategyData.count]];
            
            // 遍历显示策略详情
            for (int i = 0; i < strategyData.count; i++) {
                NSDictionary *sceneData = strategyData[i];
                [self addLogMessage:[NSString stringWithFormat:@"\n🎯 场景 %d:", i + 1]];
                [self addLogMessage:[NSString stringWithFormat:@"  📝 场景名称: %@", sceneData[@"sceneName"] ?: @"未知"]];
                [self addLogMessage:[NSString stringWithFormat:@"  📄 场景描述: %@", sceneData[@"sceneDesc"] ?: @"无"]];
                [self addLogMessage:[NSString stringWithFormat:@"  🌍 国家: %@", sceneData[@"country"] ?: @[]]];
                [self addLogMessage:[NSString stringWithFormat:@"  📺 渠道: %@", sceneData[@"channels"] ?: @[]]];
                [self addLogMessage:[NSString stringWithFormat:@"  👤 用户类型: %@", sceneData[@"userType"]]];
                
                NSArray *strategies = sceneData[@"strategies"];
                if (strategies && strategies.count > 0) {
                    [self addLogMessage:[NSString stringWithFormat:@"  📈 策略数量: %lu", (unsigned long)strategies.count]];
                    
                    for (int j = 0; j < strategies.count; j++) {
                        NSDictionary *strategy = strategies[j];
                        [self addLogMessage:[NSString stringWithFormat:@"    🔹 策略 %d:", j + 1]];
                        [self addLogMessage:[NSString stringWithFormat:@"      🆔 策略ID: %@", strategy[@"strategyId"]]];
                        [self addLogMessage:[NSString stringWithFormat:@"      📊 权重比例: %@%%", strategy[@"rate"]]];
                        
                        NSDictionary *conditions = strategy[@"conditions"];
                        if (conditions) {
                            [self addLogMessage:@"      📋 策略条件:"];
                            [self addLogMessage:[NSString stringWithFormat:@"        🎮 当前等级: %@", conditions[@"curLevel"]]];
                            [self addLogMessage:[NSString stringWithFormat:@"        📏 等级间隔: %@", conditions[@"levelInterval"]]];
                            [self addLogMessage:[NSString stringWithFormat:@"        🥇 AdMob优先: %@", conditions[@"adMobFirst"]]];
                        }
                        
                        NSDictionary *actions = strategy[@"actions"];
                        if (actions) {
                            [self addLogMessage:@"      ⚡ 策略动作:"];
                            if (actions[@"levelCombine"]) {
                                [self addLogMessage:[NSString stringWithFormat:@"        🔗 等级组合: %@", actions[@"levelCombine"]]];
                            }
                        }
                    }
                } else {
                    [self addLogMessage:@"  ⚠️ 该场景暂无策略配置"];
                }
            }
        } else {
            [self addLogMessage:@"❌ 获取产品策略失败！"];
            [self addLogMessage:[NSString stringWithFormat:@"🚫 错误信息: %@", error.localizedDescription ?: @"未知错误"]];
            [self addLogMessage:[NSString stringWithFormat:@"🔢 错误代码: %ld", (long)error.code]];
        }
        
        [self updateStatusLabel];
    }];
}

- (void)uploadFCMToken {
    [self addLogMessage:@"🔔 开始上传FCM设备令牌..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法上传FCM令牌"];
        [self addLogMessage:@"💡 提示：FCM令牌上传功能需要在SDK初始化完成后才能使用"];
        return;
    }
    
    // 获取登录用的UUID（通过DualMediationSDKPublic统一接口）和应用ID
    NSString *deviceUUID = [[DualMediationSDKPublic sharedInstance] getOrCreateLoginUUID];
    NSString *appId = @"ywoeq0rgljb6ydjh"; // 示例应用ID
    NSString *fcmToken = [NSString stringWithFormat:@"demo_fcm_token_%@", [[NSUUID UUID] UUIDString]]; // 模拟FCM令牌
    
    [self addLogMessage:[NSString stringWithFormat:@"📱 设备UUID: %@", deviceUUID]];
    [self addLogMessage:[NSString stringWithFormat:@"🆔 应用ID: %@", appId]];
    [self addLogMessage:[NSString stringWithFormat:@"🔔 FCM令牌: %@", fcmToken]];
    
    // 调用FCM令牌上传接口
    [[DualMediationSDKPublic sharedInstance] uploadFCMTokenWithAppId:appId
                                                                uuid:deviceUUID
                                                            fcmToken:fcmToken
                                                          completion:^(BOOL success, NSString * _Nullable message, NSError * _Nullable error) {
        if (success) {
            [self addLogMessage:@"✅ FCM令牌上传成功！"];
            [self addLogMessage:[NSString stringWithFormat:@"💬 服务器响应: %@", message ?: @"上传完成"]];
            [self addLogMessage:@"🎉 设备已成功注册推送服务"];
        } else {
            [self addLogMessage:@"❌ FCM令牌上传失败！"];
            [self addLogMessage:[NSString stringWithFormat:@"🚫 错误信息: %@", error.localizedDescription ?: @"未知错误"]];
            [self addLogMessage:[NSString stringWithFormat:@"🔢 错误代码: %ld", (long)error.code]];
        }
        
        [self updateStatusLabel];
    }];
}

#pragma mark - 日志管理

- (void)addLogMessage:(NSString *)message {
    if (!message) return;
    
    NSString *timestamp = [self getCurrentTimestamp];
    NSString *logEntry = [NSString stringWithFormat:@"[%@] %@", timestamp, message];
    
    // 确保所有对 logMessages 的读写都在主线程进行，避免并发读写导致的数组枚举崩溃
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.logMessages addObject:logEntry];
        
        // 限制日志条数，避免内存过大
        if (self.logMessages.count > 1000) {
            [self.logMessages removeObjectsInRange:NSMakeRange(0, 100)];
        }
        
        // 更新显示
        NSString *allLogs = [self.logMessages componentsJoinedByString:@"\n"];
        self.logDisplayView.text = allLogs;
        
        // 滚动到底部
        if (self.logDisplayView.text.length > 0) {
            NSRange bottom = NSMakeRange(self.logDisplayView.text.length - 1, 1);
            [self.logDisplayView scrollRangeToVisible:bottom];
        }
        
        [self updateStatusLabel];
    });
}

- (NSString *)getCurrentTimestamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm:ss";
    return [formatter stringFromDate:[NSDate date]];
}

- (void)updateStatusLabel {
    DualMediationSDKPublic *sdk = [DualMediationSDKPublic sharedInstance];
    NSString *status = [NSString stringWithFormat:@"📱 SDK: %@ | 📊 日志: %ld条 | 🔧 调试: %@",
                       sdk.isSDKInitialized ? @"已初始化" : @"未初始化",
                       (long)self.logMessages.count,
                       sdk.isDebugModeEnabled ? @"开启" : @"关闭"];
    
    self.statusLabel.text = status;
}

#pragma mark - 内存管理

- (void)dealloc {
    // 清理资源
}

#pragma mark - Ad Actions

- (void)loadRewarded {
    [self addLogMessage:@"🎬 检查激励视频广告状态..."];
    BOOL isReady = [[DualMediationSDKPublic sharedInstance] isRewardedVideoReady:@"rewarded_video"];
    [self addLogMessage:[NSString stringWithFormat:@"激励视频广告状态: %@", isReady ? @"已准备" : @"未准备"]];
}

- (void)showRewarded {
    [self addLogMessage:@"Showing Rewarded Ad..."];
    [[DualMediationSDKPublic sharedInstance] showRewardedVideo:@"rewarded_video" viewController:self];
}

- (void)loadInterstitial {
    [self addLogMessage:@"📱 检查插屏广告状态..."];
    BOOL isReady = [[DualMediationSDKPublic sharedInstance] isInterstitialReady:@"interstitial"];
    [self addLogMessage:[NSString stringWithFormat:@"插屏广告状态: %@", isReady ? @"已准备" : @"未准备"]];
}

- (void)showInterstitial {
    [self addLogMessage:@"Showing Interstitial Ad..."];
    [[DualMediationSDKPublic sharedInstance] showInterstitial:@"interstitial" viewController:self];
}

- (void)showSplash {
    [self addLogMessage:@"🚀 显示开屏广告..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法展示开屏广告"];
        return;
    }
    
    // 检查开屏广告是否准备就绪
    BOOL isReady = [[DualMediationSDKPublic sharedInstance] isSplashReady:@"splash"];
    [self addLogMessage:[NSString stringWithFormat:@"开屏广告状态: %@", isReady ? @"已准备" : @"未准备"]];
    
    // 使用DualMediationSDKPublic统一接口展示开屏广告
//    BOOL isReady = [[DualMediationSDKPublic sharedInstance] isSplashReady:@"splash"];
    
    if (isReady) {
        [self addLogMessage:@"✅ 开屏广告配置检查通过，开始展示"];
        
        // 使用公共接口展示开屏广告
        [[DualMediationSDKPublic sharedInstance] showSplash:@"splash" viewController:self];
        
        [self addLogMessage:@"📱 开屏广告展示请求已发送，等待回调"];
    } else {
        [self addLogMessage:@"⚠️ 开屏广告未准备就绪，跳过展示"];
    }
}

- (void)loadBanner {
    [self addLogMessage:@"📰 显示横幅广告..."];
    [self showAdContainer];
    [[DualMediationSDKPublic sharedInstance] showBanner:@"banner" containerView:self.adContainerView position:nil];
}

- (void)hideBanner {
    [self addLogMessage:@"📰 隐藏横幅广告..."];
    [[DualMediationSDKPublic sharedInstance] hideBanner:@"banner"];
    [self hideAdContainer];
}

- (void)loadNative {
    [self addLogMessage:@"📋 显示原生广告..."];
    [self showAdContainer];
    [[DualMediationSDKPublic sharedInstance] showNativeAd:@"native" containerView:self.adContainerView adView:nil];
}

#pragma mark - Banner Scene Actions

- (void)showBannerInit {
    [self addLogMessage:@"🏠 显示游戏主页Banner广告..."];
    [self showAdContainer];
    [[DualMediationSDKPublic sharedInstance] showBannerAd:@"SCENE_BANNER_INIT" position:1 enableShortScreenDetection:YES];
}

- (void)showBannerLevelEnter {
    [self addLogMessage:@"🚪 显示关卡进入Banner广告..."];
    [self showAdContainer];
    [[DualMediationSDKPublic sharedInstance] showBannerAd:@"SCENE_BANNER_LEVEL_ENTER" position:0 enableShortScreenDetection:YES];
}

- (void)showBannerLevelWin {
    [self addLogMessage:@"🏆 显示关卡胜利Banner广告..."];
    [self showAdContainer];
    [[DualMediationSDKPublic sharedInstance] showBannerAd:@"SCENE_BANNER_LEVEL_WIN" position:1 enableShortScreenDetection:YES];
}

- (void)showBannerShop {
    [self addLogMessage:@"🛒 显示商店页面Banner广告..."];
    [self showAdContainer];
    [[DualMediationSDKPublic sharedInstance] showBannerAd:@"SCENE_BANNER_SHOP" position:1 enableShortScreenDetection:YES];
}

- (void)showBannerPause {
    [self addLogMessage:@"⏸️ 显示游戏暂停Banner广告..."];
    [self showAdContainer];
    [[DualMediationSDKPublic sharedInstance] showBannerAd:@"SCENE_BANNER_GAME_PAUSE" position:1 enableShortScreenDetection:YES];
}

- (void)hideBannerScene {
    [self addLogMessage:@"❌ 隐藏场景Banner广告..."];
    [[DualMediationSDKPublic sharedInstance] hideBannerForScene:@"current"];
    [self hideAdContainer];
}


#pragma mark - Ad Delegates (Commented out - DualMediationSDKPublic uses callback-based approach)

#pragma mark - 新增功能方法

- (void)getDeviceInfo {
    [self addLogMessage:@"📱 获取设备信息..."];
    
    // 获取基本设备信息
    NSDictionary *basicInfo = [[DualMediationSDKPublic sharedInstance] getDeviceInfo];
    [self addLogMessage:[NSString stringWithFormat:@"基本信息: %@", basicInfo]];
    
    // 获取详细设备信息
    NSDictionary *detailedInfo = [[DualMediationSDKPublic sharedInstance] getDetailedDeviceInfo];
    [self addLogMessage:[NSString stringWithFormat:@"详细信息: %@", detailedInfo]];
    
    // 获取网络信息
    NSDictionary *networkInfo = [[DualMediationSDKPublic sharedInstance] getNetworkInfo];
    [self addLogMessage:[NSString stringWithFormat:@"网络信息: %@", networkInfo]];
}

- (void)testFCMPush {
    [self addLogMessage:@"🔔 测试FCM推送功能..."];
    
    // 模拟远程通知数据
    NSDictionary *userInfo = @{
        @"aps": @{
            @"alert": @"这是一条测试推送消息",
            @"badge": @1,
            @"sound": @"default"
        },
        @"custom_data": @"test_value"
    };
    
    // 处理远程通知
    [[DualMediationSDKPublic sharedInstance] handleRemoteNotification:userInfo completionHandler:nil];
    [self addLogMessage:@"已处理远程通知数据"];
    
    // 检查是否为FCM通知
    BOOL isFCMNotification = [[DualMediationSDKPublic sharedInstance] isFCMNotification:userInfo];
    [self addLogMessage:[NSString stringWithFormat:@"是否为FCM通知: %@", isFCMNotification ? @"是" : @"否"]];
}

- (void)testVibrate {
    [self addLogMessage:@"📳 测试震动功能..."];
    
    // 检查震动支持
    BOOL supportsVibration = [[DualMediationSDKPublic sharedInstance] isVibrateSupported];
    BOOL supportsHapticFeedback = [[DualMediationSDKPublic sharedInstance] isHapticFeedbackSupported];
    
    [self addLogMessage:[NSString stringWithFormat:@"震动支持: %@, 触觉反馈支持: %@",
                        supportsVibration ? @"是" : @"否",
                        supportsHapticFeedback ? @"是" : @"否"]];
    
    if (supportsVibration) {
        // 简单震动
        [[DualMediationSDKPublic sharedInstance] vibrateWithDuration:0.5];
        [self addLogMessage:@"执行简单震动"];
        
        // 延迟执行类型震动
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[DualMediationSDKPublic sharedInstance] vibrateWithType:1]; // 1 = medium intensity
            [self addLogMessage:@"执行中等强度冲击震动"];
        });
        
        // 延迟执行模式震动
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSArray *pattern = @[@100, @50, @100, @50, @200];
            [[DualMediationSDKPublic sharedInstance] vibrateWithPattern:pattern];
            [self addLogMessage:@"执行模式震动"];
        });
        
        // 获取活跃震动数量
        NSInteger activeCount = [[DualMediationSDKPublic sharedInstance] getActiveVibrateCount];
        [self addLogMessage:[NSString stringWithFormat:@"当前活跃震动数量: %ld", (long)activeCount]];
    }
}

#pragma mark - 震动调试方法

- (void)testSimpleVibrate {
    [self addLogMessage:@"📳 测试简单震动..."];
    
    // 检查震动支持
    if (![[DualMediationSDKPublic sharedInstance] isVibrateSupported]) {
        [self addLogMessage:@"❌ 设备不支持震动功能"];
        return;
    }
    
    // 测试不同时长的简单震动
    [self addLogMessage:@"🔹 执行0.3秒震动"];
    [[DualMediationSDKPublic sharedInstance] vibrateWithDuration:0.3];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 执行0.8秒震动"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithDuration:0.8];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 执行1.5秒震动"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithDuration:1.5];
    });
}

- (void)testPatternVibrate {
    [self addLogMessage:@"🎵 测试模式震动..."];
    
    if (![[DualMediationSDKPublic sharedInstance] isVibrateSupported]) {
        [self addLogMessage:@"❌ 设备不支持震动功能"];
        return;
    }
    
    // 测试不同的震动模式
    [self addLogMessage:@"🔹 SOS模式震动 (短短短-长长长-短短短)"];
    NSArray *sosPattern = @[@200, @100, @200, @100, @200, @300, @500, @100, @500, @100, @500, @300, @200, @100, @200, @100, @200];
    [[DualMediationSDKPublic sharedInstance] vibrateWithPattern:sosPattern];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 心跳模式震动"];
        NSArray *heartbeatPattern = @[@100, @100, @150, @200, @100, @100, @150, @800];
        [[DualMediationSDKPublic sharedInstance] vibrateWithPattern:heartbeatPattern];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(9.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 渐强模式震动"];
        NSArray *crescendoPattern = @[@50, @50, @100, @50, @150, @50, @200, @50, @300];
        [[DualMediationSDKPublic sharedInstance] vibrateWithPattern:crescendoPattern];
    });
}

- (void)testTypeVibrate {
    [self addLogMessage:@"⚡ 测试类型震动..."];
    
    if (![[DualMediationSDKPublic sharedInstance] isVibrateSupported]) {
        [self addLogMessage:@"❌ 设备不支持震动功能"];
        return;
    }
    
    // 测试不同类型的震动
    [self addLogMessage:@"🔹 轻微震动 (类型0)"];
    [[DualMediationSDKPublic sharedInstance] vibrateWithType:0]; // Light
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 中等震动 (类型1)"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithType:1]; // Medium
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 强烈震动 (类型2)"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithType:2]; // Heavy
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 选择震动 (类型3)"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithType:3]; // Selection
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 冲击震动 (类型4)"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithType:4]; // Impact
    });
}

- (void)testVibrateControl {
    [self addLogMessage:@"🎛️ 测试震动控制..."];
    
    if (![[DualMediationSDKPublic sharedInstance] isVibrateSupported]) {
        [self addLogMessage:@"❌ 设备不支持震动功能"];
        return;
    }
    
    // 启动一个长时间震动用于控制测试
    [self addLogMessage:@"🔹 启动长时间震动 (10秒)"];
    NSString *vibrateId = [[DualMediationSDKPublic sharedInstance] vibrateWithConfig:@{
        @"duration": @10000,
        @"type": @1
    } progressCallback:nil];
    
    if (vibrateId) {
        [self addLogMessage:[NSString stringWithFormat:@"✅ 震动已启动，ID: %@", vibrateId]];
        
        // 3秒后暂停
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self addLogMessage:@"⏸️ 暂停震动"];
            [[DualMediationSDKPublic sharedInstance] pauseVibrate:vibrateId];
        });
        
        // 5秒后恢复
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self addLogMessage:@"▶️ 恢复震动"];
            [[DualMediationSDKPublic sharedInstance] resumeVibrate:vibrateId];
        });
        
        // 7秒后取消
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self addLogMessage:@"🛑 取消震动"];
            [[DualMediationSDKPublic sharedInstance] cancelVibrate:vibrateId];
        });
    } else {
        [self addLogMessage:@"❌ 震动启动失败"];
    }
}

- (void)testPresetVibrate {
    [self addLogMessage:@"🎯 测试预设震动..."];
    
    if (![[DualMediationSDKPublic sharedInstance] isVibrateSupported]) {
        [self addLogMessage:@"❌ 设备不支持震动功能"];
        return;
    }
    
    // 使用震动服务的预设方法
    [self addLogMessage:@"🔹 成功震动"];
    [[DualMediationSDKPublic sharedInstance] vibrateWithType:6]; // Success
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 警告震动"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithType:7]; // Warning
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 错误震动"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithType:8]; // Error
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addLogMessage:@"🔹 通知震动"];
        [[DualMediationSDKPublic sharedInstance] vibrateWithType:5]; // Notification
    });
}

- (void)testVibrateStatus {
    [self addLogMessage:@"📊 查询震动状态..."];
    
    // 检查设备震动支持
    BOOL supportsVibration = [[DualMediationSDKPublic sharedInstance] isVibrateSupported];
    BOOL supportsHapticFeedback = [[DualMediationSDKPublic sharedInstance] isHapticFeedbackSupported];
    
    [self addLogMessage:[NSString stringWithFormat:@"🔹 震动支持: %@", supportsVibration ? @"✅ 是" : @"❌ 否"]];
    [self addLogMessage:[NSString stringWithFormat:@"🔹 触觉反馈支持: %@", supportsHapticFeedback ? @"✅ 是" : @"❌ 否"]];
    
    // 获取当前活跃震动数量
    NSInteger activeCount = [[DualMediationSDKPublic sharedInstance] getActiveVibrateCount];
    [self addLogMessage:[NSString stringWithFormat:@"🔹 当前活跃震动数量: %ld", (long)activeCount]];
    
    if (!supportsVibration) {
        [self addLogMessage:@"💡 提示: 当前设备不支持震动功能"];
        return;
    }
    
    // 启动几个震动来测试状态查询
    [self addLogMessage:@"🔹 启动测试震动以查看状态变化..."];
    
    // 启动3个不同的震动
    [[DualMediationSDKPublic sharedInstance] vibrateWithDuration:2.0];
    [[DualMediationSDKPublic sharedInstance] vibrateWithDuration:3.0];
    [[DualMediationSDKPublic sharedInstance] vibrateWithPattern:@[@500, @200, @500, @200, @500]];
    
    // 1秒后查询状态
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSInteger newActiveCount = [[DualMediationSDKPublic sharedInstance] getActiveVibrateCount];
        [self addLogMessage:[NSString stringWithFormat:@"🔹 启动震动后活跃数量: %ld", (long)newActiveCount]];
    });
    
    // 5秒后再次查询
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSInteger finalActiveCount = [[DualMediationSDKPublic sharedInstance] getActiveVibrateCount];
        [self addLogMessage:[NSString stringWithFormat:@"🔹 5秒后活跃数量: %ld", (long)finalActiveCount]];
    });
}

#pragma mark - iOS Lifecycle Methods

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // View lifecycle tracking is handled internally by DualMediationSDK
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // View lifecycle tracking is handled internally by DualMediationSDK
}

#pragma mark - DMSDKLifecycleDelegate Delegate Methods

- (void)onAdjustCallBack:(BOOL)isSuccess {
    NSLog(@"WonderGameSdk-MainActivity onAdjustCallBack: isSuccess: %d", isSuccess);
}

- (void)onFbCancel {
    NSLog(@"WonderGameSdk-MainActivity onFbCancel");
}

- (void)onFbError:(NSString *)msg {
    NSLog(@"WonderGameSdk-MainActivity onFbError msg: %@", msg);
}


- (void)onReviewTriggerFail:(NSString *)errorMsg {
    NSLog(@"WonderGameSdk-MainActivity onReviewTriggerFail:");
}

- (void)onShareCallBack:(BOOL)isSuccess errorMsg:(NSString *)errorMsg {
    NSLog(@"WonderGameSdk-MainActivity onShareCallBack:");
}

- (void)onBMSConfigCallBack:(BOOL)isSuccess configJsonStr:(NSString *)configJsonStr {
    NSLog(@"WonderGameSdk-MainActivity onBMSConfigCallBack:");
}

- (void)onPushMessageClick:(NSString *)pushId {
    NSLog(@"WonderGameSdk-MainActivity onPushMessageClick pushId: %@", pushId);
}

#pragma mark - Debug Methods

- (void)openIronSourceDebug {
    [self addLogMessage:@"🔧 启动IronSource调试模式..."];
    
    // 启用IronSource测试套件
    [LevelPlay setMetaDataWithKey:@"is_test_suite" value:@"enable"];
    [self addLogMessage:@"✅ IronSource测试套件已启用"];
    
    // 打开IronSource测试界面
    [LevelPlay launchTestSuite:self];
    [self addLogMessage:@"📱 IronSource测试界面已打开"];
    
    [LevelPlay validateIntegration];
}

- (void)openMAXDebug {
    [self addLogMessage:@"🔧 启动MAX调试模式..."];
    
    // 打开MAX调试界面
    [[ALSdk shared] showMediationDebugger];
    [self addLogMessage:@"📱 MAX调试界面已打开"];
}

#pragma mark - Interstitial Ad Methods

- (void)setupInterstitialManager {
    [self addLogMessage:@"📱 初始化插屏广告管理器..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法设置插屏广告管理器"];
        [self addLogMessage:@"💡 提示：请先初始化SDK"];
        return;
    }
    
    // 注意：根据架构规则，ViewController不应直接操作内部组件
    // 插屏广告管理器的初始化应该在SDK内部自动完成
    // 这里仅做演示，实际使用时应通过DualMediationSDKPublic统一接口
    
    [self addLogMessage:@"✅ 插屏广告管理器初始化完成"];
    [self addLogMessage:@"📱 SDK内部已自动配置插屏广告管理器"];
}

- (void)setupSceneManagerExample {
    [self addLogMessage:@"🎯 配置场景管理器..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法配置场景管理器"];
        return;
    }
    
    // 注意：根据架构规则，ViewController不应直接操作内部组件
    // 场景管理器的配置应该通过DualMediationSDKPublic统一接口或在SDK内部自动完成
    // 这里仅做演示说明
    
    [self addLogMessage:@"✅ 场景管理器配置完成"];
    [self addLogMessage:@"⏰ SDK内部已自动配置场景触发间隔"];
    [self addLogMessage:@"⏳ SDK内部已自动配置关卡等待间隔"];
}

- (void)setupSceneInterceptorExample {
    [self addLogMessage:@"🛡️ 配置场景拦截器..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法配置场景拦截器"];
        return;
    }
    
    // 注意：根据架构规则，ViewController不应直接操作内部组件
    // 场景拦截器的配置应该通过DualMediationSDKPublic统一接口或在SDK内部自动完成
    // 拦截器参数应由后端广告策略控制，不可外部修改
    
    [self addLogMessage:@"✅ 场景拦截器配置完成"];
    [self addLogMessage:@"⏱️ SDK内部已自动配置最小展示间隔"];
    [self addLogMessage:@"📊 SDK内部已自动配置每日最大展示次数"];
    
    // 场景状态检查应通过DualMediationSDKPublic统一接口
    NSArray *sceneStrings = @[@"SCENE_INTER_LEVEL_WIN", @"SCENE_INTER_LEVEL_FAIL", @"SCENE_INTER_LEVEL_RETRY"];
    NSArray *sceneNames = @[@"关卡胜利", @"关卡失败", @"关卡重试"];
    
    for (NSInteger i = 0; i < sceneStrings.count; i++) {
        NSString *sceneString = sceneStrings[i];
        NSString *sceneName = sceneNames[i];
        
        BOOL isReady = [[DualMediationSDKPublic sharedInstance] isInterstitialReadyForScene:sceneString];
        
        [self addLogMessage:[NSString stringWithFormat:@"🎯 场景 %@:", sceneName]];
        [self addLogMessage:[NSString stringWithFormat:@"  广告状态: %@", isReady ? @"就绪" : @"未就绪"]];
    }
}

- (void)showInterLevelWin {
    [self addLogMessage:@"🏆 展示关卡胜利插屏广告..."];
    [[DualMediationSDKPublic sharedInstance] showInterstitialForScene:@"SCENE_INTER_LEVEL_WIN"];
}

- (void)showInterLevelFail {
    [self addLogMessage:@"💀 展示关卡失败插屏广告..."];
    [[DualMediationSDKPublic sharedInstance] showInterstitialForScene:@"SCENE_INTER_LEVEL_FAIL"];
}

- (void)showInterLevelRetry {
    [self addLogMessage:@"🔄 展示关卡重玩插屏广告..."];
    [[DualMediationSDKPublic sharedInstance] showInterstitialForScene:@"SCENE_INTER_LEVEL_RETRY"];
}

- (void)showInterPlayTime {
    [self addLogMessage:@"⏰ 手动触发游戏时长场景..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法触发游戏时长场景"];
        return;
    }
    
    // 注意：根据架构规则，应通过DualMediationSDKPublic统一接口触发场景
    // 这里使用场景化插屏广告接口替代直接操作内部组件
    // 游戏时长场景使用字符串常量，因为它是内置自动触发场景
    [[DualMediationSDKPublic sharedInstance] showInterstitialForScene:@"SCENE_INTER_PLAY_TIME"];
    [self addLogMessage:@"✅ 游戏时长场景已触发"];
}

- (void)showInterLevelWait {
    [self addLogMessage:@"⏳ 手动触发关卡等待场景..."];
    
    // 检查SDK是否已初始化
    if (![DualMediationSDKPublic sharedInstance].isSDKInitialized) {
        [self addLogMessage:@"❌ SDK未初始化，无法触发关卡等待场景"];
        return;
    }
    
    // 注意：根据架构规则，应通过DualMediationSDKPublic统一接口触发场景
    // 这里使用场景化插屏广告接口替代直接操作内部组件
    // 关卡等待场景使用字符串常量，因为它是内置自动触发场景
    [[DualMediationSDKPublic sharedInstance] showInterstitialForScene:@"SCENE_INTER_LEVEL_WAIT"];
    [self addLogMessage:@"✅ 关卡等待场景已触发"];
}

// 移除了showInterstitialForScene方法，直接使用DualMediationSDKPublic的公共接口

#pragma mark - DMAdDelegate Methods

// 通用广告回调方法
- (void)dmAdManager:(DMAdManager *)adManager didLoadAd:(NSString *)adId adType:(NSString *)adType {
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]✅ 广告加载成功 - ID: %@, 类型: %@", adId, adType]];
}

- (void)dmAdManager:(DMAdManager *)adManager didFailToLoadAd:(NSString *)adId adType:(NSString *)adType error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]❌ 广告加载失败 - ID: %@, 类型: %@", adId, adType]];
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]🚫 错误信息: %@", error.localizedDescription]];
}

- (void)dmAdManager:(DMAdManager *)adManager didShowAd:(NSString *)adId adType:(NSString *)adType {
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]👁️ 广告展示成功 - ID: %@, 类型: %@", adId, adType]];
}

- (void)dmAdManager:(DMAdManager *)adManager didFailToShowAd:(NSString *)adId adType:(NSString *)adType error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]❌ 广告展示失败 - ID: %@, 类型: %@", adId, adType]];
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]🚫 错误信息: %@", error.localizedDescription]];
}

- (void)dmAdManager:(DMAdManager *)adManager didClickAd:(NSString *)adId adType:(NSString *)adType {
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]👆 广告点击 - ID: %@, 类型: %@", adId, adType]];
}

- (void)dmAdManager:(DMAdManager *)adManager didCloseAd:(NSString *)adId adType:(NSString *)adType {
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]❌ 广告关闭 - ID: %@, 类型: %@", adId, adType]];
}

// 激励视频特殊回调
- (void)dmAdManager:(DMAdManager *)adManager didCompleteRewardedVideo:(NSString *)adId reward:(NSDictionary *)reward {
    [self addLogMessage:[NSString stringWithFormat:@"[广告回调]🎁 激励视频完成 - ID: %@, 奖励: %@", adId, reward]];
}

#pragma mark - 激励视频场景化回调

/**
 * 激励视频开始展示（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didShowRewardedVideoForScene:(NSString *)scene adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"【激励视频回调】🎬 [场景化] 激励视频开始展示 - 场景: %@, ID: %@", scene, adId]];
    
    // 根据不同场景进行特殊处理
    if ([scene isEqualToString:@"level_complete"]) {
        [self addLogMessage:@"🎮 关卡完成场景激励视频开始播放"];
    } else if ([scene isEqualToString:@"shop_purchase"]) {
        [self addLogMessage:@"🛒 商店购买场景激励视频开始播放"];
    } else if ([scene isEqualToString:@"daily_reward"]) {
        [self addLogMessage:@"🎁 每日奖励场景激励视频开始播放"];
    } else {
        [self addLogMessage:[NSString stringWithFormat:@"📱 场景 %@ 激励视频开始播放", scene]];
    }
}

/**
 * 激励视频关闭（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didCloseRewardedVideoForScene:(NSString *)scene adId:(NSString *)adId isUserRewarded:(BOOL)isUserRewarded {
    [self addLogMessage:[NSString stringWithFormat:@"【激励视频回调】❌ [场景化] 激励视频关闭 - 场景: %@, ID: %@, 获得奖励: %@", scene, adId, isUserRewarded ? @"是" : @"否"]];
    
    // 根据是否获得奖励和场景进行不同处理
    if (isUserRewarded) {
        if ([scene isEqualToString:@"level_complete"]) {
            [self addLogMessage:@"🎉 关卡完成奖励已发放，可以进入下一关"];
            // 这里可以添加具体的奖励发放逻辑
        } else if ([scene isEqualToString:@"shop_purchase"]) {
            [self addLogMessage:@"💰 商店购买奖励已发放，获得额外折扣"];
            // 这里可以添加商店折扣逻辑
        } else if ([scene isEqualToString:@"daily_reward"]) {
            [self addLogMessage:@"🎁 每日奖励已发放，明天再来领取"];
            // 这里可以添加每日奖励逻辑
        } else {
            [self addLogMessage:[NSString stringWithFormat:@"✅ 场景 %@ 奖励已发放", scene]];
            
            // 显示奖励发放弹窗
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"获得奖励" 
                                                                                     message:[NSString stringWithFormat:@"恭喜！您已完成观看激励视频，场景 %@ 的奖励已发放！", scene] 
                                                                              preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:okAction];
                
                // 在主线程上显示弹窗
                UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
                while (topVC.presentedViewController) {
                    topVC = topVC.presentedViewController;
                }
                [topVC presentViewController:alertController animated:YES completion:nil];
            });
        }
    } else {
        [self addLogMessage:[NSString stringWithFormat:@"⚠️ 场景 %@ 激励视频未完整观看，未获得奖励", scene]];
    }
}

/**
 * 激励视频展示失败（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didFailToShowRewardedVideoForScene:(NSString *)scene error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"【激励视频回调】❌ [场景化] 激励视频展示失败 - 场景: %@", scene]];
    [self addLogMessage:[NSString stringWithFormat:@"【激励视频回调】🚫 错误信息: %@", error.localizedDescription]];
    
    // 根据不同场景提供备选方案
    if ([scene isEqualToString:@"level_complete"]) {
        [self addLogMessage:@"🎮 关卡完成激励视频失败，可以直接进入下一关"];
    } else if ([scene isEqualToString:@"shop_purchase"]) {
        [self addLogMessage:@"🛒 商店购买激励视频失败，请稍后重试"];
    } else if ([scene isEqualToString:@"daily_reward"]) {
        [self addLogMessage:@"🎁 每日奖励激励视频失败，请检查网络连接"];
    } else {
        [self addLogMessage:[NSString stringWithFormat:@"【激励视频回调】📱 场景 %@ 激励视频失败，请稍后重试", scene]];
    }
}

#pragma mark ----- 插屏广告场景化回调 - 使用字符串场景名称
- (void)dmAdManager:(DMAdManager *)adManager didLoadInterstitialForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]✅ 插屏广告加载成功 - 场景: %@, ID: %@", sceneName, adId]];
}

- (void)dmAdManager:(DMAdManager *)adManager didFailToLoadInterstitialForScene:(NSString *)sceneName error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]❌ 插屏广告加载失败 - 场景: %@", sceneName]];
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]🚫 错误信息: %@", error.localizedDescription]];
}

- (void)dmAdManager:(DMAdManager *)adManager didShowInterstitialForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]👁️ 插屏广告展示成功 - 场景: %@, ID: %@", sceneName, adId]];
}

- (void)dmAdManager:(DMAdManager *)adManager didFailToShowInterstitialForScene:(NSString *)sceneName error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]❌ 插屏广告展示失败 - 场景: %@", sceneName]];
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]🚫 错误信息: %@", error.localizedDescription]];
}

- (void)dmAdManager:(DMAdManager *)adManager didClickInterstitialForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]👆 插屏广告点击 - 场景: %@, ID: %@", sceneName, adId]];
}

- (void)dmAdManager:(DMAdManager *)adManager didCloseInterstitialForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"[插屏广告回调]❌ 插屏广告关闭 - 场景: %@, ID: %@", sceneName, adId]];
    
    // 广告关闭后的逻辑处理
    if ([sceneName isEqualToString:@"SCENE_INTER_LEVEL_WIN"]) {
        [self addLogMessage:@"🎮 关卡胜利广告关闭，可以进入下一关"];
    } else if ([sceneName isEqualToString:@"SCENE_INTER_LEVEL_FAIL"]) {
        [self addLogMessage:@"🎮 关卡失败广告关闭，可以重新开始游戏"];
    } else if ([sceneName isEqualToString:@"SCENE_INTER_LEVEL_RETRY"]) {
        [self addLogMessage:@"🎮 关卡重玩广告关闭，可以重新尝试"];
    }
}

#pragma mark - Banner广告场景化回调

/**
 * Banner广告加载成功（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didLoadBannerForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"✅ Banner广告加载成功 - 场景: %@, ID: %@", sceneName, adId]];
}

/**
 * Banner广告加载失败（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didFailToLoadBannerForScene:(NSString *)sceneName error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"❌ Banner广告加载失败 - 场景: %@", sceneName]];
    [self addLogMessage:[NSString stringWithFormat:@"🚫 错误信息: %@", error.localizedDescription]];
}

/**
 * Banner广告即将展示（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager willShowBannerForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"🔄 Banner广告即将展示 - 场景: %@, ID: %@", sceneName, adId]];
}

/**
 * Banner广告展示成功（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didShowBannerForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"👁️ Banner广告展示成功 - 场景: %@, ID: %@", sceneName, adId]];
}

/**
 * Banner广告展示失败（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didFailToShowBannerForScene:(NSString *)sceneName error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"❌ Banner广告展示失败 - 场景: %@", sceneName]];
    [self addLogMessage:[NSString stringWithFormat:@"🚫 错误信息: %@", error.localizedDescription]];
}

/**
 * Banner广告被点击（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didClickBannerForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"👆 Banner广告点击 - 场景: %@, ID: %@", sceneName, adId]];
}

/**
 * Banner广告被移除（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didRemoveBannerForScene:(NSString *)sceneName adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"🗑️ Banner广告移除 - 场景: %@, ID: %@", sceneName, adId]];
    
    // Banner广告移除后的逻辑处理
    [self addLogMessage:[NSString stringWithFormat:@"🎮 场景 %@ 的Banner广告已移除，界面已清理", sceneName]];
}

/**
 * Banner广告尺寸变化（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didChangeBannerSizeForScene:(NSString *)sceneName adId:(NSString *)adId size:(CGSize)size {
    [self addLogMessage:[NSString stringWithFormat:@"📏 Banner广告尺寸变化 - 场景: %@, ID: %@", sceneName, adId]];
    [self addLogMessage:[NSString stringWithFormat:@"📐 新尺寸: %.0f x %.0f", size.width, size.height]];
}

#pragma mark - 开屏广告场景化回调

/**
 * 开屏广告展示成功（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didShowSplashAdForScene:(NSString *)scene adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"【开屏广告回调】🚀 开屏广告展示成功 - 场景: %@, ID: %@", scene, adId]];
    
    // 根据不同场景进行特殊处理
    if ([scene isEqualToString:@"SCENE_SPLASH_COOL"]) {
        [self addLogMessage:@"❄️ 冷启动场景开屏广告展示"];
        // 冷启动场景的特殊逻辑
        [self trackSplashAdShow:scene adId:adId];
    } else if ([scene isEqualToString:@"SCENE_SPLASH_HOT"]) {
        [self addLogMessage:@"🔥 热启动场景开屏广告展示"];
        // 热启动场景的特殊逻辑
        [self trackSplashAdShow:scene adId:adId];
    } else {
        [self addLogMessage:[NSString stringWithFormat:@"📱 场景 %@ 开屏广告展示", scene]];
    }
}

/**
 * 开屏广告关闭（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didCloseSplashAdForScene:(NSString *)scene adId:(NSString *)adId isUserClicked:(BOOL)isUserClicked {
    [self addLogMessage:[NSString stringWithFormat:@"【开屏广告回调】❌ 开屏广告关闭 - 场景: %@, ID: %@, 用户点击: %@", scene, adId, isUserClicked ? @"是" : @"否"]];
    
    // 根据是否用户点击和场景进行不同处理
    if (isUserClicked) {
        [self addLogMessage:[NSString stringWithFormat:@"【开屏广告回调】👆 场景 %@ 开屏广告被用户点击关闭", scene]];
        // 用户点击的特殊处理逻辑
        [self handleSplashAdClick:scene adId:adId];
    } else {
        [self addLogMessage:[NSString stringWithFormat:@"【开屏广告回调】⏰ 场景 %@ 开屏广告自动关闭", scene]];
        // 自动关闭的处理逻辑
    }
    
    // 开屏广告关闭后，进入主界面
    [self enterMainInterface];
}

/**
 * 开屏广告展示失败（场景化）
 */
- (void)dmAdManager:(DMAdManager *)adManager didFailToShowSplashAdForScene:(NSString *)scene error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"【开屏广告回调】❌ 开屏广告展示失败 - 场景: %@", scene]];
    [self addLogMessage:[NSString stringWithFormat:@"【开屏广告回调】🚫 错误信息: %@", error.localizedDescription]];
    
    // 根据不同场景提供备选方案
    if ([scene isEqualToString:@"SCENE_SPLASH_COOL"]) {
        [self addLogMessage:@"❄️ 冷启动开屏广告失败，直接进入主界面"];
    } else if ([scene isEqualToString:@"SCENE_SPLASH_HOT"]) {
        [self addLogMessage:@"🔥 热启动开屏广告失败，直接进入主界面"];
    } else {
        [self addLogMessage:[NSString stringWithFormat:@"【开屏广告回调】📱 场景 %@ 开屏广告失败，直接进入主界面", scene]];
    }
    
    // 处理广告失败事件
    [self handleSplashAdFailure:scene error:error];
    
    // 开屏广告失败后，直接进入主界面
    [self enterMainInterface];
}

#pragma mark - Helper Methods

// 移除了基于DMInterstitialScene枚举的辅助方法，现在直接使用字符串常量

#pragma mark - 开屏广告辅助方法

/**
 * 跟踪开屏广告展示事件
 */
- (void)trackSplashAdShow:(NSString *)scene adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"📊 跟踪开屏广告展示 - 场景: %@, ID: %@", scene, adId]];
    // 这里可以添加具体的跟踪逻辑，如发送到分析平台
}

/**
 * 处理开屏广告点击事件
 */
- (void)handleSplashAdClick:(NSString *)scene adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"👆 处理开屏广告点击 - 场景: %@, ID: %@", scene, adId]];
    // 这里可以添加点击后的处理逻辑，如跳转到特定页面
}

/**
 * 处理开屏广告失败事件
 */
- (void)handleSplashAdFailure:(NSString *)scene error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"❌ 处理开屏广告失败 - 场景: %@, 错误: %@", scene, error.localizedDescription]];
    // 这里可以添加失败后的处理逻辑，如记录错误日志
}

/**
 * 进入主界面
 */
- (void)enterMainInterface {
    [self addLogMessage:@"🏠 进入应用主界面"];
    // 这里可以添加进入主界面的逻辑，如切换视图控制器
}

#pragma mark - 免广告功能按钮事件处理

/**
 * 设置免广告按钮点击事件
 */
- (void)setRemoveAdAction {
    [self addLogMessage:@"🚫 点击设置免广告按钮"];
    
    // 创建选择器让用户选择要禁用的广告类型
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"设置免广告"
                                                                             message:@"请选择要禁用的广告类型"
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    // 添加各种广告类型选项
    [alertController addAction:[UIAlertAction actionWithTitle:@"禁用激励视频广告" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeReward isRemove:YES];
        [self addLogMessage:@"✅ 已禁用激励视频广告"];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"禁用插屏广告" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeInsert isRemove:YES];
        [self addLogMessage:@"✅ 已禁用插屏广告"];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"禁用横幅广告" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeBanner isRemove:YES];
        [self addLogMessage:@"✅ 已禁用横幅广告"];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"禁用开屏广告" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeSplash isRemove:YES];
        [self addLogMessage:@"✅ 已禁用开屏广告"];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"禁用原生广告" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeNative isRemove:YES];
        [self addLogMessage:@"✅ 已禁用原生广告"];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

/**
 * 查询免广告状态按钮点击事件
 */
- (void)checkRemoveAdAction {
    [self addLogMessage:@"🔍 查询免广告状态"];
    
    // 查询各种广告类型的免广告状态
    BOOL rewardRemoved = [[DualMediationSDKPublic sharedInstance] isRemoveAd:DMAdBanTypeReward];
    BOOL interstitialRemoved = [[DualMediationSDKPublic sharedInstance] isRemoveAd:DMAdBanTypeInsert];
    BOOL bannerRemoved = [[DualMediationSDKPublic sharedInstance] isRemoveAd:DMAdBanTypeBanner];
    BOOL splashRemoved = [[DualMediationSDKPublic sharedInstance] isRemoveAd:DMAdBanTypeSplash];
    BOOL nativeRemoved = [[DualMediationSDKPublic sharedInstance] isRemoveAd:DMAdBanTypeNative];
    
    [self addLogMessage:[NSString stringWithFormat:@"🎁 激励视频广告: %@", rewardRemoved ? @"已禁用" : @"正常"]];
    [self addLogMessage:[NSString stringWithFormat:@"📱 插屏广告: %@", interstitialRemoved ? @"已禁用" : @"正常"]];
    [self addLogMessage:[NSString stringWithFormat:@"📰 横幅广告: %@", bannerRemoved ? @"已禁用" : @"正常"]];
    [self addLogMessage:[NSString stringWithFormat:@"🚀 开屏广告: %@", splashRemoved ? @"已禁用" : @"正常"]];
    [self addLogMessage:[NSString stringWithFormat:@"🖼️ 原生广告: %@", nativeRemoved ? @"已禁用" : @"正常"]];
}

/**
 * 禁用激励视频广告按钮点击事件
 */
- (void)removeRewardAdAction {
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeReward isRemove:YES];
    [self addLogMessage:@"🎁❌ 已禁用激励视频广告"];
}

/**
 * 禁用插屏广告按钮点击事件
 */
- (void)removeInterstitialAdAction {
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeInsert isRemove:YES];
    [self addLogMessage:@"📱❌ 已禁用插屏广告"];
}

/**
 * 禁用横幅广告按钮点击事件
 */
- (void)removeBannerAdAction {
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeBanner isRemove:YES];
    [self addLogMessage:@"📰❌ 已禁用横幅广告"];
}

/**
 * 禁用开屏广告按钮点击事件
 */
- (void)removeSplashAdAction {
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeSplash isRemove:YES];
    [self addLogMessage:@"🚀❌ 已禁用开屏广告"];
}

/**
 * 禁用原生广告按钮点击事件
 */
- (void)removeNativeAdAction {
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeNative isRemove:YES];
    [self addLogMessage:@"🖼️❌ 已禁用原生广告"];
}

/**
 * 禁用所有广告按钮点击事件
 */
- (void)removeAllAdsAction {
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeAll isRemove:YES];
    [self addLogMessage:@"🚫 已禁用所有广告（除激励视频外）"];
}

/**
 * 恢复所有广告按钮点击事件
 */
- (void)restoreAllAdsAction {
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeInsert isRemove:NO];
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeBanner isRemove:NO];
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeSplash isRemove:NO];
    [[DualMediationSDKPublic sharedInstance] setRemoveAd:DMAdBanTypeNative isRemove:NO];
    [self addLogMessage:@"✅ 已恢复所有广告"];
}

#pragma mark - 场景化原生广告按钮事件处理

/**
 * 显示顶部原生广告按钮点击事件
 */
- (void)showNativeTopAction:(UIButton *)sender {
    [self addLogMessage:@"🖼️⬆️ 点击显示顶部原生广告按钮"];
    
    // 调用场景化原生广告接口显示顶部广告
    [[DualMediationSDKPublic sharedInstance] showNative:@"SCENE_NATIVE_SETTLEMENT" position:0];
}

/**
 * 显示底部原生广告按钮点击事件
 */
- (void)showNativeBottomAction:(UIButton *)sender {
    [self addLogMessage:@"🖼️⬇️ 点击显示底部原生广告按钮"];
    
    // 调用场景化原生广告接口显示底部广告
    [[DualMediationSDKPublic sharedInstance] showNative:@"SCENE_NATIVE_SETTLEMENT" position:1];
}

/**
 * 隐藏原生广告按钮点击事件
 */
- (void)hideNativeAction:(UIButton *)sender {
    [self addLogMessage:@"🖼️❌ 点击隐藏原生广告按钮"];
    
    // 调用场景化原生广告接口隐藏广告
    [[DualMediationSDKPublic sharedInstance] hideNative:@"SCENE_NATIVE_SETTLEMENT"];
}

/**
 * 检查原生广告就绪状态按钮点击事件
 */
- (void)checkNativeReadyAction:(UIButton *)sender {
    [self addLogMessage:@"🖼️🔍 点击检查原生广告就绪状态按钮"];
    
    // 检查原生广告是否就绪
    BOOL isReady = [[DualMediationSDKPublic sharedInstance] isNativeAdReady:@"SCENE_NATIVE_SETTLEMENT"];
    [self addLogMessage:[NSString stringWithFormat:@"🖼️📊 原生广告就绪状态: %@", isReady ? @"已就绪" : @"未就绪"]];
}

#pragma mark - DMAdDelegate 原生广告代理回调方法

/**
 * 原生广告显示成功回调
 */
- (void)onNativeShow:(NSString *)scene position:(NSInteger)position {
    NSString *positionStr = (position == 0) ? @"顶部" : @"底部";
    [self addLogMessage:[NSString stringWithFormat:@"🖼️🎉 场景 %@ 原生广告显示成功，位置: %@", scene, positionStr]];
    
    // 跟踪原生广告展示事件
    [self trackNativeAdShow:scene adId:@"统一接口"];
}

/**
 * 原生广告显示失败回调
 */
- (void)onNativeShowFail:(NSString *)scene position:(NSInteger)position error:(NSError *)error {
    NSString *positionStr = (position == 0) ? @"顶部" : @"底部";
    [self addLogMessage:[NSString stringWithFormat:@"🖼️💥 场景 %@ 原生广告显示失败，位置: %@，错误: %@", scene, positionStr, error.localizedDescription]];
    
    // 处理原生广告显示失败事件
    [self handleNativeAdShowFailure:scene error:error];
}

/**
 * 原生广告移除回调
 */
- (void)onNativeRemoved:(NSString *)scene {
    [self addLogMessage:[NSString stringWithFormat:@"🖼️👋 场景 %@ 原生广告已移除", scene]];
}

/**
 * 原生广告点击回调
 */
- (void)onNativeClick:(NSString *)scene {
    [self addLogMessage:[NSString stringWithFormat:@"🖼️👆 场景 %@ 原生广告被点击", scene]];
    
    // 处理原生广告点击事件
    [self handleNativeAdClick:scene adId:@"统一接口"];
}

#pragma mark - 原生广告辅助方法

/**
 * 跟踪原生广告展示事件
 */
- (void)trackNativeAdShow:(NSString *)scene adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"📊 跟踪原生广告展示 - 场景: %@, ID: %@", scene, adId]];
    // 这里可以添加具体的跟踪逻辑，如发送到分析平台
}

/**
 * 处理原生广告点击事件
 */
- (void)handleNativeAdClick:(NSString *)scene adId:(NSString *)adId {
    [self addLogMessage:[NSString stringWithFormat:@"👆 处理原生广告点击 - 场景: %@, ID: %@", scene, adId]];
    // 这里可以添加点击后的处理逻辑，如跳转到特定页面
}

/**
 * 处理原生广告显示失败事件
 */
- (void)handleNativeAdShowFailure:(NSString *)scene error:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"❌ 处理原生广告显示失败 - 场景: %@, 错误: %@", scene, error.localizedDescription]];
    // 这里可以添加失败后的处理逻辑，如记录错误日志或重试
}

#pragma mark - Facebook功能方法实现

/**
 * Facebook登录按钮点击事件
 */
- (void)facebookLoginAction {
    [self addLogMessage:@"📘 开始Facebook登录..."];
    
    // 通过DualMediationSDKPublic调用Facebook登录
    [[DualMediationSDKPublic sharedInstance] facebookLogin];
}

/**
 * Facebook登出按钮点击事件
 */
- (void)facebookLogoutAction {
    [self addLogMessage:@"📘 开始Facebook登出..."];
    
    // 通过DualMediationSDKPublic调用Facebook登出
    [[DualMediationSDKPublic sharedInstance] facebookLogout];
    [self addLogMessage:@"✅ Facebook登出成功"];
}

/**
 * 获取Facebook用户信息按钮点击事件
 */
- (void)facebookGetUserInfoAction {
    [self addLogMessage:@"👤 获取Facebook用户信息..."];
    
    // 设置DMDelegate代理
    [[DualMediationSDKPublic sharedInstance] setAdDelegate:self];
    
    // 通过DualMediationSDKPublic调用获取用户信息
    [[DualMediationSDKPublic sharedInstance] getFacebookUserInfo];
}

/**
 * Facebook分享按钮点击事件
 */
- (void)facebookShareAction {
    [self addLogMessage:@"📤 开始Facebook分享..."];
    
    // 设置DMDelegate代理
    [[DualMediationSDKPublic sharedInstance] setAdDelegate:self];
    
    // 通过DualMediationSDKPublic调用Facebook分享
    [[DualMediationSDKPublic sharedInstance] facebookShareLink:@"https://github.com/dualmediationsdk"
                                                         quote:@"这是一个来自DualMediation SDK的测试分享内容，展示Facebook分享功能的集成效果。"];
}

/**
 * Facebook分享图片按钮点击事件
 */
- (void)facebookShareImageAction {
    [self addLogMessage:@"🖼️ 开始Facebook图片分享..."];
    
    // 设置DMDelegate代理
    [[DualMediationSDKPublic sharedInstance] setAdDelegate:self];
    
    // 创建测试图片
    UIImage *testImage = [self createTestImage];
    
    // 通过DualMediationSDKPublic调用Facebook图片分享
    [[DualMediationSDKPublic sharedInstance] facebookShareImage:testImage];
}

/**
 * Facebook状态检查按钮点击事件
 */
- (void)facebookCheckStatusAction {
    [self addLogMessage:@"📊 检查Facebook状态..."];
    
    // 通过DualMediationSDKPublic检查登录状态
    BOOL isLoggedIn = [[DualMediationSDKPublic sharedInstance] isFacebookLoggedIn];
    [self addLogMessage:[NSString stringWithFormat:@"🔐 Facebook登录状态: %@", isLoggedIn ? @"已登录" : @"未登录"]];
    
    // 通过DualMediationSDKPublic获取访问令牌
    NSString *accessToken = [[DualMediationSDKPublic sharedInstance] getFacebookAccessToken];
    if (accessToken) {
        [self addLogMessage:[NSString stringWithFormat:@"🔑 访问令牌: %@...", [accessToken substringToIndex:MIN(20, accessToken.length)]]];
    } else {
        [self addLogMessage:@"🔑 访问令牌: 无"];
    }
    
    // 通过DualMediationSDKPublic获取SDK版本
//    NSString *sdkVersion = [[DualMediationSDKPublic sharedInstance] getFacebookSDKVersion];
//    [self addLogMessage:[NSString stringWithFormat:@"📱 Facebook SDK版本: %@", sdkVersion]];
    
    // 通过DualMediationSDKPublic获取缓存的用户信息
    NSDictionary *cachedUserInfo = [[DualMediationSDKPublic sharedInstance] getCachedFacebookUserInfo];
    if (cachedUserInfo) {
        [self addLogMessage:[NSString stringWithFormat:@"👤 缓存用户信息: %@", cachedUserInfo[@"name"] ?: @"未知"]];
    } else {
        [self addLogMessage:@"👤 缓存用户信息: 无"];
    }
}

#pragma mark - DMAdDelegate Facebook回调方法实现

/**
 * Facebook登录成功回调
 */
- (void)dmFacebookLoginSuccess:(NSDictionary *)result {
    [self addLogMessage:@"✅ Facebook登录成功！"];
    
    if (result[@"user_id"]) {
        [self addLogMessage:[NSString stringWithFormat:@"👤 用户ID: %@", result[@"user_id"]]];
    }
    
    if (result[@"access_token"]) {
        NSString *token = result[@"access_token"];
        [self addLogMessage:[NSString stringWithFormat:@"🔑 访问令牌: %@...", [token substringToIndex:MIN(20, token.length)]]];
    }
    
    if (result[@"granted_permissions"]) {
        [self addLogMessage:[NSString stringWithFormat:@"🔐 授权权限: %@", result[@"granted_permissions"]]];
    }
}

/**
 * Facebook登录失败回调
 */
- (void)dmFacebookLoginError:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"❌ Facebook登录失败: %@", error.localizedDescription]];
    
    // 根据错误类型提供用户友好的提示
    if (error.code == 1) { // 用户取消
        [self addLogMessage:@"ℹ️ 用户取消了登录操作"];
    } else if (error.code == 2) { // 网络错误
        [self addLogMessage:@"🌐 网络连接错误，请检查网络设置"];
    } else {
        [self addLogMessage:[NSString stringWithFormat:@"🔧 错误代码: %ld", (long)error.code]];
    }
}

/**
 * Facebook登录取消回调
 */
- (void)dmFacebookLoginCancel {
    [self addLogMessage:@"⚠️ Facebook登录被用户取消"];
}

/**
 * Facebook用户信息获取成功回调
 */
- (void)dmFacebookUserInfoSuccess:(NSDictionary *)userInfo {
    [self addLogMessage:@"✅ Facebook用户信息获取成功！"];
    
    if (userInfo[@"name"]) {
        [self addLogMessage:[NSString stringWithFormat:@"👤 姓名: %@", userInfo[@"name"]]];
    }
    
    if (userInfo[@"email"]) {
        [self addLogMessage:[NSString stringWithFormat:@"📧 邮箱: %@", userInfo[@"email"]]];
    }
    
    if (userInfo[@"id"]) {
        [self addLogMessage:[NSString stringWithFormat:@"🆔 用户ID: %@", userInfo[@"id"]]];
    }
    
    if (userInfo[@"picture"]) {
        NSDictionary *picture = userInfo[@"picture"];
        if (picture[@"data"] && picture[@"data"][@"url"]) {
            [self addLogMessage:[NSString stringWithFormat:@"🖼️ 头像URL: %@", picture[@"data"][@"url"]]];
        }
    }
}

/**
 * Facebook用户信息获取失败回调
 */
- (void)dmFacebookUserInfoError:(NSError *)error {
    [self addLogMessage:[NSString stringWithFormat:@"❌ Facebook用户信息获取失败: %@", error.localizedDescription]];
}

/**
 * Facebook分享完成回调
 */
- (void)dmFacebookShareComplete:(BOOL)success message:(NSString *)message {
    if (success) {
        [self addLogMessage:@"✅ Facebook分享成功！"];
        [self addLogMessage:[NSString stringWithFormat:@"🎉 %@", message]];
    } else {
        [self addLogMessage:@"❌ Facebook分享失败"];
        [self addLogMessage:[NSString stringWithFormat:@"📝 失败原因: %@", message]];
    }
}

#pragma mark - 内购功能方法

/**
 * 启动内购按钮点击事件
 */
- (void)launchInAppPurchaseAction {
    [self addLogMessage:@"🛒 启动内购功能..."];
    
    // 这里使用一个测试商品ID，实际使用时应该从配置或用户选择中获取
    NSString *testProductId = @"small_st_jam";
    
    if (testProductId && testProductId.length > 0) {
        [self addLogMessage:[NSString stringWithFormat:@"📦 商品ID: %@", testProductId]];
        
        // 调用DualMediationSDKPublic的内购方法
        [[DualMediationSDKPublic sharedInstance] launchInAppPurchase:testProductId];
        
        [self addLogMessage:@"⏳ 内购请求已发送，等待处理..."];
    } else {
        [self addLogMessage:@"❌ 商品ID不能为空"];
    }
}

/**
 * 恢复购买按钮点击事件
 */
- (void)restoreInAppPurchaseAction {
    [self addLogMessage:@"🔄 恢复购买功能..."];
    
    // 这里使用一个测试商品ID，实际使用时应该从配置或用户选择中获取
    NSString *testProductId = @"remove_ads_pack_jam";
    
    if (testProductId && testProductId.length > 0) {
        [self addLogMessage:[NSString stringWithFormat:@"📦 恢复商品ID: %@", testProductId]];
        
        // 调用DualMediationSDKPublic的恢复购买方法
        [[DualMediationSDKPublic sharedInstance] restoreInAppPurchase:testProductId];
        
        [self addLogMessage:@"⏳ 恢复购买请求已发送，等待处理..."];
    } else {
        [self addLogMessage:@"❌ 商品ID不能为空"];
    }
}

/**
 * 获取商品列表按钮点击事件
 */
- (void)requestProductListAction {
    [self addLogMessage:@"📋 获取商品列表功能..."];
    
    // 这里使用测试商品ID列表，实际使用时应该从配置中获取
    NSArray *testProductIds = @[@"small_st_jam", @"medium_st_jam", @"big_st_jam"];
    
    if (testProductIds && testProductIds.count > 0) {
        [self addLogMessage:[NSString stringWithFormat:@"📦 请求商品数量: %lu", (unsigned long)testProductIds.count]];
        for (NSString *productId in testProductIds) {
            [self addLogMessage:[NSString stringWithFormat:@"📦 商品ID: %@", productId]];
        }
        
        // 调用DualMediationSDKPublic的获取商品列表方法
        [[DualMediationSDKPublic sharedInstance] requestProductsList];
        
        [self addLogMessage:@"⏳ 商品列表请求已发送，等待处理..."];
    } else {
        [self addLogMessage:@"❌ 商品ID列表不能为空"];
    }
}

/**
 * 消耗性内购按钮点击事件
 */
- (void)consumableInAppPurchaseAction {
    [self addLogMessage:@"🛒 启动消耗性内购功能..."];
    
    // 消耗性商品ID，实际使用时应该从配置中获取
    NSString *consumableProductId = @"small_st_jam";
    
    if (consumableProductId && consumableProductId.length > 0) {
        [self addLogMessage:[NSString stringWithFormat:@"📦 消耗性商品ID: %@", consumableProductId]];
        [self addLogMessage:@"💰 商品类型: 消耗性商品（可重复购买）"];
        
        // 调用DualMediationSDKPublic的内购方法
        [[DualMediationSDKPublic sharedInstance] launchInAppPurchase:consumableProductId];
        
        [self addLogMessage:@"⏳ 消耗性内购请求已发送，等待处理..."];
    } else {
        [self addLogMessage:@"❌ 消耗性商品ID不能为空"];
    }
}

/**
 * 非消耗型内购按钮点击事件
 */
- (void)nonConsumableInAppPurchaseAction {
    [self addLogMessage:@"💎 启动非消耗型内购功能..."];
    
    // 非消耗型商品ID，实际使用时应该从配置中获取
    NSString *nonConsumableProductId = @"revive_pack_jam";
    
    if (nonConsumableProductId && nonConsumableProductId.length > 0) {
        [self addLogMessage:[NSString stringWithFormat:@"📦 非消耗型商品ID: %@", nonConsumableProductId]];
        [self addLogMessage:@"💎 商品类型: 非消耗型商品（永久有效）"];
        
        // 调用DualMediationSDKPublic的内购方法
        [[DualMediationSDKPublic sharedInstance] launchInAppPurchase:nonConsumableProductId];
        
        [self addLogMessage:@"⏳ 非消耗型内购请求已发送，等待处理..."];
    } else {
        [self addLogMessage:@"❌ 非消耗型商品ID不能为空"];
    }
}

#pragma mark - 辅助方法

/**
 * 创建测试图片
 */
- (UIImage *)createTestImage {
    // 创建一个简单的测试图片
    CGSize size = CGSizeMake(300, 200);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    
    // 设置背景色
    [[UIColor colorWithRed:0.24 green:0.35 blue:0.60 alpha:1.0] setFill];
    UIRectFill(CGRectMake(0, 0, size.width, size.height));
    
    // 添加文字
    NSString *text = @"DualMediation\nSDK Test";
    NSDictionary *attributes = @{
        NSFontAttributeName: [UIFont boldSystemFontOfSize:24],
        NSForegroundColorAttributeName: [UIColor whiteColor]
    };
    
    CGSize textSize = [text sizeWithAttributes:attributes];
    CGPoint textPoint = CGPointMake((size.width - textSize.width) / 2, (size.height - textSize.height) / 2);
    [text drawAtPoint:textPoint withAttributes:attributes];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark - 内购回调

/**
 * 内购开始回调
 * @param adManager 广告管理器
 * @param productId 商品ID
 */
- (void)dmAdManager:(DMAdManager *)adManager didBeginInAppPurchase:(NSString *)productId {
    [self addLogMessage:@"[IAP][内购回调]🛒 内购开始..."];
    [self addLogMessage:[NSString stringWithFormat:@"📦 商品ID: %@", productId ?: @"未知"]];
}

/**
 * 内购成功回调
 * @param adManager 广告管理器
 * @param productId 商品ID
 * @param transactionId 交易ID
 */
- (void)dmAdManager:(DMAdManager *)adManager didSuccessInAppPurchase:(NSString *)productId transactionId:(NSString *)transactionId {
    [self addLogMessage:@"[IAP][内购回调]✅ 内购成功！"];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品ID: %@", productId ?: @"未知"]];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🆔 交易ID: %@", transactionId ?: @"未知"]];
    
    // 显示发货成功弹窗
    [self showInAppPurchaseSuccessAlert:productId transactionId:transactionId];
}

/**
 * 内购失败回调
 * @param adManager 广告管理器
 * @param productId 商品ID
 * @param error 错误信息
 */
- (void)dmAdManager:(DMAdManager *)adManager didFailInAppPurchase:(NSString *)productId error:(NSError *)error {
    [self addLogMessage:@"[IAP][内购回调]❌ 内购失败"];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品ID: %@", productId ?: @"未知"]];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🔧 错误信息: %@", error.localizedDescription ?: @"未知错误"]];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🔢 错误代码: %ld", (long)error.code]];
}

/**
 * 恢复购买开始回调
 * @param adManager 广告管理器
 * @param productId 商品ID（可能为空，表示全量恢复）
 */
- (void)dmAdManager:(DMAdManager *)adManager didBeginRestoreInAppPurchase:(NSString * _Nullable)productId {
    [self addLogMessage:@"[IAP][内购回调]🔄 恢复购买开始..."];
    if (productId) {
        [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 恢复商品ID: %@", productId]];
    } else {
        [self addLogMessage:@"[IAP]📦 恢复类型: 全量恢复"];
    }
}

/**
 * 恢复购买成功回调
 * @param adManager 广告管理器
 * @param productId 商品ID
 * @param transactionId 交易ID
 */
- (void)dmAdManager:(DMAdManager *)adManager didSuccessRestoreInAppPurchase:(NSString *)productId transactionId:(NSString *)transactionId {
    [self addLogMessage:@"[IAP][内购回调]✅ 恢复购买成功！"];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品ID: %@", productId ?: @"未知"]];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🆔 交易ID: %@", transactionId ?: @"未知"]];
    
    [self acknowledgeOrder:transactionId];
}

/**
 * 恢复购买失败回调
 * @param adManager 广告管理器
 * @param productId 商品ID（可能为空，表示全量恢复）
 * @param error 错误信息
 */
- (void)dmAdManager:(DMAdManager *)adManager didFailRestoreInAppPurchase:(NSString * _Nullable)productId error:(NSError *)error {
    [self addLogMessage:@"[IAP][内购回调]❌ 恢复购买失败"];
    if (productId) {
        [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品ID: %@", productId]];
    } else {
        [self addLogMessage:@"[IAP]📦 恢复类型: 全量恢复"];
    }
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🔧 错误信息: %@", error.localizedDescription ?: @"未知错误"]];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🔢 错误代码: %ld", (long)error.code]];
}

/**
 * 商品列表获取成功回调
 * @param adManager 广告管理器
 * @param products 商品列表
 */
- (void)dmAdManager:(DMAdManager *)adManager didReceiveProductList:(NSArray *)products {
    [self addLogMessage:@"[IAP][内购回调]✅ 商品列表获取成功！"];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品数量: %lu", (unsigned long)products.count]];
    
    for (NSInteger i = 0; i < products.count; i++) {
        id product = products[i];
        if ([product isKindOfClass:[SKProduct class]]) {
            SKProduct *pro = (SKProduct *)product;
            NSLog(@"内购预请求标题：%@", pro.localizedTitle);
            NSLog(@"内购预请求描述：%@", pro.localizedDescription);
            NSLog(@"内购预请求价格：%@", pro.price);
            NSLog(@"内购预请求ID：%@", pro.productIdentifier);
            NSLog(@"内购预请求价格货币符号%@", pro.priceLocale.currencyCode);
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 标题: %@", (long)(i+1), pro.localizedTitle ?: @"未知"]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 描述: %@", (long)(i+1), pro.localizedDescription ?: @"未知"]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 价格: %@", (long)(i+1), pro.price ?: (id)@"未知"]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld ID: %@", (long)(i+1), pro.productIdentifier ?: @"未知"]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 货币: %@", (long)(i+1), pro.priceLocale.currencyCode ?: @"未知"]];
        } else if ([product isKindOfClass:[NSDictionary class]]) {
            NSDictionary *productDict = (NSDictionary *)product;
            NSString *productId = productDict[@"productIdentifier"] ?: productDict[@"productId"] ?: productDict[@"id"] ?: @"未知";
            NSString *title = productDict[@"localizedTitle"] ?: productDict[@"title"] ?: @"未知";
            NSString *desc = productDict[@"localizedDescription"] ?: productDict[@"description"] ?: @"未知";
            id priceObj = productDict[@"price"] ?: @"未知";
            NSString *currency = productDict[@"currencyCode"] ?: @"未知";
            NSLog(@"内购预请求标题：%@", title);
            NSLog(@"内购预请求描述：%@", desc);
            NSLog(@"内购预请求价格：%@", priceObj);
            NSLog(@"内购预请求ID：%@", productId);
            NSLog(@"内购预请求价格货币符号%@", currency);
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 标题: %@", (long)(i+1), title]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 描述: %@", (long)(i+1), desc]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 价格: %@", (long)(i+1), priceObj]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld ID: %@", (long)(i+1), productId]];
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld 货币: %@", (long)(i+1), currency]];
        } else {
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 商品%ld: %@", (long)(i+1), product]];
            NSLog(@"内购预请求原始对象：%@", product);
        }
    }
    
}

/**
 * 商品列表获取失败回调
 * @param adManager 广告管理器
 * @param error 错误信息
 */
- (void)dmAdManager:(DMAdManager *)adManager didFailToReceiveProductList:(NSError *)error {
    [self addLogMessage:@"[IAP][内购回调]❌ 商品列表获取失败"];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🔧 错误信息: %@", error.localizedDescription ?: @"未知错误"]];
    [self addLogMessage:[NSString stringWithFormat:@"[IAP]🔢 错误代码: %ld", (long)error.code]];
}
#pragma mark - 启动时未核销订单检查

/**
 * 启动时检查未核销订单
 */
- (void)checkUnacknowledgedOrdersOnStartup {
    [self addLogMessage:@"[IAP]🔍 检查未核销订单..."];
    
    // 调用未核销接口
    [[DualMediationSDKPublic sharedInstance] fetchUnacknowledgedOrdersWithSuccessCallback:^(NSArray * _Nullable orders) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self handleUnacknowledgedOrders:orders];
        });
    } failureCallback:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]❌ 获取未核销订单失败: %@", error.localizedDescription ?: @"未知错误"]];
        });
    }];
}

/**
 * 处理未核销订单
 * @param orders 未核销订单列表
 */
- (void)handleUnacknowledgedOrders:(NSArray *)orders {
    if (orders && orders.count > 0) {
        [self addLogMessage:[NSString stringWithFormat:@"[IAP]📦 发现 %lu 个未核销订单", (unsigned long)orders.count]];
        
        // 显示发货成功弹窗
        [self showDeliverySuccessAlertWithOrders:orders];
    } else {
        [self addLogMessage:@"[IAP]✅ 没有未核销订单"];
    }
}

/**
 * 显示发货成功弹窗
 * @param orders 未核销订单列表
 */
- (void)showDeliverySuccessAlertWithOrders:(NSArray *)orders {
    NSString *title = @"🎉 发货成功";
    NSString *message = [NSString stringWithFormat:@"您有 %lu 个商品已成功发货，请确认收货！", (unsigned long)orders.count];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    // 确认按钮 - 在回调中调用核销接口
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认收货"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
        [self acknowledgeOrdersAfterDeliveryConfirmation:orders];
    }];
    
    // 取消按钮
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"稍后处理"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
        [self addLogMessage:@"[IAP]⏸️ 用户选择稍后处理未核销订单"];
    }];
    
    [alert addAction:confirmAction];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    [self addLogMessage:@"[IAP]📱 显示发货成功弹窗"];
}

/**
 * 显示内购成功发货弹窗
 * @param productId 商品ID
 * @param transactionId 交易ID
 */
- (void)showInAppPurchaseSuccessAlert:(NSString *)productId transactionId:(NSString *)transactionId {
    NSString *title = @"🎉 发货成功";
    NSString *message = [NSString stringWithFormat:@"商品购买成功！\n商品ID: %@\n交易ID: %@", productId ?: @"未知", transactionId ?: @"未知"];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    // 确认按钮
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
        [self addLogMessage:@"[IAP]✅ 用户确认收到商品"];
        [self acknowledgeOrder:transactionId];
    }];
    
    [alert addAction:confirmAction];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    [self addLogMessage:@"[IAP]📱 显示内购成功发货弹窗"];
}

/**
 * 显示核销成功弹窗
 * @param originalTransactionId 原始交易ID
 */
- (void)showAcknowledgeSuccessAlert:(NSString *)originalTransactionId {
    NSString *title = @"✅ 核销成功";
    NSString *message = [NSString stringWithFormat:@"[IAP]订单核销成功！\n交易ID: %@", originalTransactionId ?: @"未知"];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    // 确认按钮
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
        [self addLogMessage:@"[IAP]✅ 用户确认核销成功提示"];
    }];
    
    [alert addAction:confirmAction];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    [self addLogMessage:@"[IAP]📱 显示核销成功弹窗"];
}

/**
 * 发货确认后核销订单
 * @param orders 需要核销的订单列表
 */
- (void)acknowledgeOrdersAfterDeliveryConfirmation:(NSArray *)orders {
    [self addLogMessage:@"[IAP]🔄 开始核销订单..."];
    
    for (NSDictionary *order in orders) {
        NSString *originalTransactionId = order[@"original_transaction_id"];
        if (originalTransactionId && originalTransactionId.length > 0) {
            [self acknowledgeOrder:originalTransactionId];
        } else {
            [self addLogMessage:@"[IAP]⚠️ 订单缺少原始交易ID，跳过核销"];
        }
    }
}

/**
 * 核销单个订单
 * @param originalTransactionId 原始交易ID
 */
- (void)acknowledgeOrder:(NSString *)originalTransactionId {
    [self addLogMessage:[NSString stringWithFormat:@"🔄 核销订单: %@", originalTransactionId]];
    
    [[DualMediationSDKPublic sharedInstance] acknowledgeInAppPurchaseWithOriginalTransactionId:originalTransactionId
                                                                                 successCallback:^(id _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]✅ 订单核销成功: %@", originalTransactionId]];
            // 显示核销成功弹窗
            [self showAcknowledgeSuccessAlert:originalTransactionId];
        });
    } failureCallback:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self addLogMessage:[NSString stringWithFormat:@"[IAP]❌ 订单核销失败: %@ - %@", originalTransactionId, error.localizedDescription ?: @"未知错误"]];
        });
    }];
}

#pragma mark - 新增按钮方法实现

/**
 * 核销订单按钮点击事件
 */
- (void)acknowledgeOrderAction {
    [self addLogMessage:@"[IAP]🔄 手动核销订单测试..."];
    
    // 使用示例交易ID进行核销测试
    NSString *testTransactionId = @"1000000123456789";
    [self acknowledgeOrder:testTransactionId];
}

/**
 * 查询未核销订单按钮点击事件
 */
- (void)fetchUnacknowledgedOrdersAction {
    [self addLogMessage:@"[IAP]📋 手动查询未核销订单..."];
    
    // 调用现有的未核销订单检查方法
    [self checkUnacknowledgedOrdersOnStartup];
}

/**
 * 显示应用信息界面
 */
- (void)showAppInfoAction {
    [self addLogMessage:@"[IAP]📱 打开应用信息界面..."];
    
    [[DualMediationSDKPublic sharedInstance] showAppInfoViewController:self];
}

@end
 
